php - 向 WP 循环中的最后一项添加额外的类

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

我需要的是第四个:

        <div class="popular-post-item"> 

添加另一个名为 .last 的类

有什么想法吗?

最佳答案

您需要使用 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; ?>

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

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

关于php - 向 WP 循环中的最后一项添加额外的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9610985/

相关文章:

css - wordpress 标题和容器宽度不会保持在 100%

wordpress - 在 cakephp 3.0 中重写 cakephp 路径

wordpress - 是否有内置功能来显示选项页面的验证错误?

php - 获取在 WooCommerce 中用于一种产品的订单和运输的税率

php - 检查键是否是数组中的最后一个元素?

php - 哪些 CMS 可以与 Phalcon 框架一起使用?

javascript - Vue - 通过 vue 组件传递 prop 数组导致未定义错误

php - 有没有办法从 GET 请求中删除提交按钮?

Java 正则表达式 : UNGREEDY flag

php - Mysql fetch() 返回 FALSE