如何在WordPress循环中正确获取页面的最新评论日期
WordPress获取页面最新评论日期的解决方案
问题原因
get_comment_date()第二个参数要求传入评论ID,你之前传入文章ID$post->ID的写法不符合函数规则,无法正常返回对应文章的评论日期- 原有代码循环仅遍历页面对象,没有提前获取对应页面的评论数据,直接调用无参数的
get_comment_date()会默认读取全局缓存的第一条评论对象,因此所有页面输出的都是同一个日期
最简实现方案
不需要复杂查询,调用WordPress内置的get_comments接口获取当前页面最新1条已审核评论即可:
// 传入当前页面ID,查询最新1条公开评论 $latest_comment = get_comments([ 'post_id' => $post->ID, 'number' => 1, 'status' => 'approve', 'orderby' => 'comment_date', 'order' => 'DESC' ]); // 存在评论则取最新评论日期,无评论则默认取文章发布日期 $latest_comment_date = !empty($latest_comment) ? get_comment_date('d/m/Y', $latest_comment[0]->comment_ID) : get_the_date('d/m/Y', $post->ID);
适配原有逻辑的完整修改代码
你可以直接替换原有代码段,修改后逻辑如下:
$args = array( 'posts_per_page' => 10, 'post_type' => 'page', 'orderby' => 'date', 'category_name' => 'MyName' ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); // 获取当前页面评论总数 $comments_count = get_comments_number( $post->ID ); // 获取当前页面最新评论日期 $latest_comment = get_comments( array( 'post_id' => $post->ID, 'number' => 1, 'status' => 'approve', 'orderby' => 'comment_date', 'order' => 'DESC' ) ); $comment_date_class = !empty($latest_comment) ? get_comment_date( 'd/m/Y', $latest_comment[0]->comment_ID ) : get_the_date( 'd/m/Y', $post->ID ); ?> <div class="comments <?php echo esc_attr($comment_date_class); ?>"> <span><?php echo esc_html($comments_count); ?></span> </div> <?php endforeach; // 重置文章数据,避免影响后续全局查询逻辑 wp_reset_postdata(); ?>
注:代码中新增了esc_attr、esc_html转义函数,避免输出异常内容引发安全问题
内容的提问来源于stack exchange,提问作者Pepe
相关产品推荐
相关产品推荐

