Creating a gallery of featured images from custom post type

To create the gallery you want, follow these steps:

1) Navigate to your theme folder and create a file named cpt-gallery.php

2) Copy and paste this code into the file

<?php 
    /*
    Template Name: Custom Post Type Gallery
    Description: Creates a gallery of featured images from a custom post type
    Notes: Make sure you have support for thumbnails enabled
    */

    get_header(); 

    // Query the custom post type to display
    $args = array('post_type' => 'CUSTOM POST TYPE');
    $query = new WP_Query( $args );
?>

<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
    <?php if ( has_post_thumbnail() ): ?>
        <a href="https://wordpress.stackexchange.com/questions/111336/<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
    <?php endif; ?>
<?php endwhile; endif; ?>
<?php get_footer(); ?>

3) In WordPress, create a new page named “Home” and on the right side under “Page Attributes” select the template “Custom Post Type Gallery” from the menu.

4) Navigate to Settings > Reading and under the option “Front page displays,” select “A static page” and then select the page you created labeled “Home.” Save those changes.

NOTES: Make sure that you replace the word “CUSTOM POST TYPE” with the actual name of your custom post type. This code will pull in each custom post type you’ve defined, loop through them and then display a thumbnail of the featured image for that post with a link to it.

I’ve tested this so it should work for you just fine. Let me know if you need further clarification.

Leave a Comment

tech