如何在单篇文章页正确显示对应评论?请求排查问题
解决comments_template()显示其他文章评论的问题
嘿,这个问题我之前也碰到过,根源其实很明确:你在调用comments_template()之前,用了自定义的WP_Query循环(也就是$the_query->the_post()这行),这个操作会覆盖WordPress全局的$post对象。当循环结束后,全局$post已经变成了最后一篇同分类文章的对象,所以comments_template()会误以为当前要显示的是这篇文章的评论,而不是你最初的那篇单篇文章。
给你两个靠谱的解决方案,优先推荐第一种:
方案1:用wp_reset_postdata()重置全局对象(官方推荐)
在自定义循环结束后,调用wp_reset_postdata()就能恢复全局$post到原始文章的状态,这样comments_template()就会加载正确的评论了。修改后的代码如下:
<?php if(have_posts()): while(have_posts()): the_post(); ?> // 显示单篇文章并获取文章分类 <?php endwhile;endif; ?> <?php if(isset($cats_arr) && !empty($cats_arr)){ $args = array( 'category__in' => $cats_arr, 'posts_per_page'=>3, 'post__not_in' => array( $post->ID ) ); $the_query= new wp_query($args); if($the_query->have_posts()): while($the_query->have_posts()): $the_query->the_post(); ?> // 显示同分类文章标题和图片 <?php endwhile; // 关键:重置全局post对象,回到原始文章 wp_reset_postdata(); endif; } ?> <?php comments_template(); ?>
方案2:手动指定评论对应的文章ID
如果因为某些原因不想重置查询,也可以在调用comments_template()时,手动传入原始文章的ID。需要先提前保存原始文章ID,避免被循环覆盖:
// 先保存原始文章的ID,防止被后续循环覆盖 <?php $original_post_id = $post->ID; ?> <?php if(have_posts()): while(have_posts()): the_post(); ?> // 显示单篇文章并获取文章分类 <?php endwhile;endif; ?> <?php if(isset($cats_arr) && !empty($cats_arr)){ $args = array( 'category__in' => $cats_arr, 'posts_per_page'=>3, 'post__not_in' => array( $original_post_id ) ); $the_query= new wp_query($args); if($the_query->have_posts()): while($the_query->have_posts()): $the_query->the_post(); ?> // 显示同分类文章标题和图片 <?php endwhile; endif; } ?> // 手动指定原始文章ID加载评论 <?php comments_template('', false, $original_post_id); ?>
小提醒
优先选方案1哦,wp_reset_postdata()是WordPress官方推荐的规范做法,不仅能解决评论的问题,还能避免后续其他模板函数(比如the_title()、the_permalink())出现异常,确保全局上下文始终正确。
内容的提问来源于stack exchange,提问作者peyman
相关产品推荐
相关产品推荐

