【问题标题】:How to only display thumbnail for first post of Category如何仅显示类别第一篇文章的缩略图
【发布时间】:2012-10-24 01:55:42
【问题描述】:

我有这段代码来显示所有类别的帖子和它们的缩略图。


<?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; ?>

但现在我只想为类别的第一篇文章显示缩略图。 显然,前类别有 4 个帖子,我显示 4 个帖子但只有第一个帖子有缩略图,3 个帖子只有标题和永久链接

【问题讨论】:

  • 在这段代码中看不到任何缩略图?
  • 对不起。我忘了插入它。我正在使用

标签: php wordpress thumbnails displaytag


【解决方案1】:

将 the_post_thumbnail 添加到您的输出中,并包含一个 $postNumber 以跟踪您所在的帖子编号。然后,使用 if 语句,您可以包含 the_post_thumbnail 调用。如果您想将它包含在前 2 个中,请将 if 更改为 $postNumber

<?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; ?>

【讨论】:

  • 我使用 来获取缩略图。
  • 是的。抱歉,我忘了删除这些变量。该函数确实有两个参数,所以如果你想稍微自定义缩略图,你可以。
【解决方案2】:

快速修复可能是添加一个计数变量..

<?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; ?>

【讨论】:

  • have_posts()) : $recent->the_post(); ?>
    • // 显示缩略图的代码 } ?>
【解决方案3】:
<?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; ?>

【讨论】:

  • 我使用 来获取缩略图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
  • 2011-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多