我用这个来提取四个最受欢迎的基于评论的帖子:
<?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">
添加另一个类,称为最后一个
有什么想法吗?
您需要将查询结果的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的原因是,一个编号是基于零的索引,另一个是基于一的计数。)
另一种选择是使用伪选择器,但这取决于您需要支持的浏览器。
使用$pc->post_count获取WP_Query返回的帖子数,并将其与迭代器进行比较。
<?php
$pc = new WP_Query('orderby=comment_count&posts_per_page=4');
$count = $pc->post_count;
$i = 0;
?>
<?php while ($pc->have_posts()) : $pc->the_post(); ?>
<div class="popular-post-item<?php if ($i === $count) echo ' 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
// incriment counter
$i++;
?>
<?php endwhile; ?>