0

I have 6 posts with a featured image set for each. I have created a template file called portfolio-template.php. I have set the portfolio page to use that template file. Inside portfolio-template.php I have this minimal code:

<?php 
/*
Template Name: portfolio template
*/
?>

<?php get_header(); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  <?php the_post_thumbnail(); ?>
<?php endwhile; endif; ?>

<?php get_footer(); ?>

All I am trying to do is pull in the featured image of the posts and display it on the page. But this does not seem to work. The page is blank. I don't know what I am doing wrong but it is probably something simple. Any help will be greatly appreciated.

Thanks

1 Answer 1

0

You won't get anything back from your template simply because the loop returns what is in the main query object for that specific page. To see what is actually in the main query object, you should do var_dump( $wp_query ); outside the loop.

To display custom content on a page template, you will need to run a custom query to pull in the required posts. pre_get_posts does not work on page templates, so you will need WP_Query or get_posts to run a custom query

EXAMPLE:

$args = [
    'posts_per_page' => 6,
    // Add any extra query parameters here according to https://codex.wordpress.org/Class_Reference/WP_Query
];
$q = new WP_Query( $args );

if ( $q->have_posts() ) {
    while ( $q->have_posts() ) {
    $q->the_post();

        if ( has_post_thumbnail() ) {
            the_post_thumbnail();
        }

    }
    wp_reset_postdata();
}
2
  • wow my friend. You just taught me something I hadn't realized and now makes total sense. Thanks you sooooo much.
    – agon024
    Commented Nov 10, 2015 at 18:43
  • My pleasure, glad I could help. Enjoy ;-) Commented Nov 10, 2015 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.