简体   繁体   English

如何仅显示类别的第一篇文章的缩略图

[英]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 显然,前类别有4个帖子,我显示4个帖子但只有第一个帖子有缩略图,3个帖子仍然只有标题和永久链接

quick fix could be adding a counting variable.. 快速修复可能是添加计数变量..

<?php i = 1; ?>
<?php while($recent->have_posts()) : $recent->the_post(); ?>

<ul>
    <li>
<?php if(i==1){ 
  // code to display thumbnail
 } ?>

            <a href="<?php the_permalink(); ?>">
            <?php the_title(); ?>
            </a>
       </li>
</ul>
<?php i++; ?>
<?php endwhile; ?>

Add the_post_thumbnail to your output and include a $postNumber to track what number post you're on. 将the_post_thumbnail添加到您的输出中并包含$ postNumber以跟踪您发布的帖子号码。 Then, with an if statement, you can include the_post_thumbnail call. 然后,使用if语句,您可以包含the_post_thumbnail调用。 If you want to include it on the first 2, change the if to $postNumber <= 2 如果要将其包含在前2个中,请将if更改为$ 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; ?>
<?php $recent = new WP_Query(); ?>
<?php $recent->query( 'cat=1&showposts=5' ); ?>
<?php $is_first_post = true; ?>

<?php while( $recent->have_posts() ) : $recent->the_post(); ?>
    <ul>
        <li>
                <a href="<?php the_permalink(); ?>">
                <?php the_title(); ?>
                </a>

                <?php 
                if ( $is_first_post  && has_post_thumbnail() ) {
                    the_post_thumbnail(); 
                    $is_first_post = false; 
                }
                ?>


           </li>
    </ul>
<?php endwhile; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM