在WP循环中为最后一项添加额外的类

Mar*_*rkP 3 php wordpress

我正在使用它来根据评论推出四个最受欢迎的帖子:

        <?php
            $pc = new WP_Query('orderby=comment_count&posts_per_page=4'); ?>
            <?php while ($pc->have_posts()) : $pc->the_post(); ?>
            <div class="popular-post-item">
            <span class="popular-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post-links"><?php the_title(); ?></a></span>
            <span class="popular-author">by: <?php the_author() ?></span> 
            <a href="<?php the_permalink(); ?>" class="action">Read Full Article</a>
            </div>
        <?php endwhile; ?> 
Run Code Online (Sandbox Code Playgroud)

我需要的是第四个:

        <div class="popular-post-item"> 
Run Code Online (Sandbox Code Playgroud)

添加另一个名为.last的类

有任何想法吗?

jus*_*eez 8

您将要使用三元组的查询结果current_postpost_count属性.

与某些人建议的不同,您不必创建单独的计数器变量(因为该current_post属性已经是结果的索引号):

<?php
$pc = new WP_Query('orderby=comment_count&posts_per_page=4');
while ($pc->have_posts()) :
    $pc->the_post();
?>
<div class="popular-post-item<?php echo $pc->current_post + 1 === $pc->post_count ? ' last' : '' ?>">
    <span class="popular-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post-links"><?php the_title(); ?></a></span>
    <span class="popular-author">by: <?php the_author() ?></span>
    <a href="<?php the_permalink(); ?>" class="action">Read Full Article</a>
</div>
<?php endwhile; ?>
Run Code Online (Sandbox Code Playgroud)

(请注意,添加的代码部分是正确的<?php echo $pc->current_post + 1 === $pc->post_count ? ' last' : '' ?>,并且您必须将1添加到当前帖子编号的原因是因为一个数字是从零开始的索引,而另一个是基于一的数字.)

另一种选择是使用伪选择器,但这取决于您需要支持哪些浏览器.