You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让WordPress指定帖子最新评论在Bootstrap轮播中添加active类?

你的思路完全可行,只需要调整两处代码就能实现需求:

  • 首先修改评论查询参数,把获取条数从1改成3,这样才能拿到3条评论用于轮播
  • 在循环里判断当前评论是否是第一条(因为你按评论日期倒序排列,第一条就是最新评论),给它加上active类,其他评论不加

修改后的完整代码如下:

<?php
$args = array(
    'status'  => 'approve',
    'number'  => '3', // 改成获取3条评论
    'post_id' => 9,
    'orderby' => 'comment_date',
    'order'   => 'DESC'
);
$comments = get_comments( $args );

// 遍历评论时带上索引
foreach ( $comments as $index => $comment ) :
    // 只有第一条(最新)评论添加active类
    $active = $index === 0 ? ' active' : '';
    echo '<div class="carousel-item'.$active.'">
        <div class="carousel-caption">
            <span class="fad fa-quote-right" aria-hidden="true"></span>';
            comment_text($comment->comment_ID); // 传入评论ID,确保显示当前评论内容
            echo '<div id="image-caption">&mdash; <a href="'.$comment->comment_author_url.'" target="_blank">'.$comment->comment_author.'</a></div>
        </div><!-- carousel-caption -->
    </div><!-- carousel-item -->';
endforeach;
?>

额外注意:调用comment_text()的时候最好传入当前评论的ID($comment->comment_ID),避免因为全局评论对象不一致导致显示内容错误。

内容的提问来源于stack exchange,提问作者Aki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:55:25