Search code examples
phpwordpressthumbnailsdisplaytag

How to only display thumbnail for first post of Category


I have this code to show all post of category and thumbnail of them.


<?php $recent = new WP_Query(); ?>
<?php $recent->query('cat=1&showposts=5'); ?>
<?php while($recent->have_posts()) : $recent->the_post(); ?>
<ul>
    <li>
            <a href="<?php the_permalink(); ?>">
            <?php the_title(); ?>
            </a>
       </li>
</ul>
<?php endwhile; ?>

But now I only want show thumbnail for first post of category. clearly,ex Category have 4 post, I show 4 post but only first post have thumbnail,3 posts remain only have title and permalink


Solution

  • Add the_post_thumbnail to your output and include a $postNumber to track what number post you're on. Then, with an if statement, you can include the_post_thumbnail call. If you want to include it on the first 2, change the if to $postNumber <= 2

    <?php $recent = new WP_Query(); 
    <?php $recent->query('cat=1&showposts=5'); ?>
    <?php $postNumber = 1; ?>
    <?php while($recent->have_posts()) : $recent->the_post(); ?>
    <ul>
        <li>
                <a href="<?php the_permalink(); ?>">
                <?php 
                    if($postNumber<=1){
                        the_post_thumbnail();
                    }
                    $postNumber++;
                 ?> 
                <?php the_title(); ?>
                </a>
           </li>
    </ul>
    <?php endwhile; ?>