首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向WP循环中的最后一项添加额外的类

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

Stack Overflow用户
提问于 2012-03-08 07:51:49
回答 2查看 5.8K关注 0票数 3

我用这个来从评论中找出四个最受欢迎的帖子:

代码语言:javascript
复制
        <?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; ?> 

我需要的是第四个:

代码语言:javascript
复制
        <div class="popular-post-item"> 

添加另一个名为.last的类

有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-03-08 08:38:21

使用$pc->post_count获取WP_Query返回的post数,并将其与迭代器进行比较。

代码语言:javascript
复制
    <?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; ?> 
票数 3
EN

Stack Overflow用户

发布于 2012-03-08 08:45:58

您需要将查询结果的current_postpost_count属性与三元组一起使用。

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

代码语言:javascript
复制
<?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的原因是因为一个数字是从零开始的索引,另一个是从1开始的计数。)

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

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9610985

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档