我正在使用它根据评论提取四个最受欢迎的帖子:
<?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; ?>
我需要的是第四个:
<div class="popular-post-item">
添加另一个名为 .last 的类
有什么想法吗?
最佳答案
您需要使用 current_post
和 post_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; ?>
(请注意,添加的代码部分只是 <?php echo $pc->current_post + 1 === $pc->post_count ? ' last' : '' ?>
,您必须将 1 添加到当前帖子编号的原因是因为一个数字是从零开始的索引,另一个是从一开始的索引基于计数。)
另一种选择是使用伪选择器,但这取决于您需要支持的浏览器。
关于php - 向 WP 循环中的最后一项添加额外的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9610985/