WordPress:帮助获得正确的评论以显示在单个帖子上

问题描述

我正在构建自定义Wordpress主题,并且在任何单个帖子上显示所有评论,而不仅仅是该帖子的评论。显然,我希望仅显示对该帖子发表的评论。

<?php

//Get only the approved comments
$args = array(
    'status' => 'approve'
);

// The comment Query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
 
// Comment Loop
if ( $comments ) {
  
  echo '<ol class="post-comments">';
  
  foreach ( $comments as $comment ) {
  
?>
 
 <li class="post-comment">
 
   <div class="comment-avatar">
     <div><?php echo get_avatar( $comment,32 ); ?></div>
   </div>
   
  <div class="comment-content">
    <div class="comment-meta">
      <p class="comment-author"><?php echo $comment->comment_author; ?></p> 
      <p class="comment-date"> <?php echo $comment->comment_date; ?></p>
    </div> 
    <p class="comment-text"><?php echo $comment->comment_content; ?></p> 
  </div>
  
 </li>
 
 <?php
  }
    echo '</ol>';
} else {
 echo 'No comments found.';
}
?>

我本质上是在使用这段代码,是我直接从wordpress.org获得的

 <?php 
$args = array( 
    // args here 
); 
 
// The Query 
 
$comments_query = new WP_Comment_Query( $args ); 
$comments = $comments_query->comments;
 
// Comment Loop 
 
if ( $comments ) { 
    foreach ( $comments as $comment ) { 
        echo $comment->comment_content;
    }
} else {
    echo 'No comments found.';
}
?>

解决方法

为了只显示特定帖子ID的评论,您必须在post_id参数中传递相关的帖子ID,例如:

$args = array(
    'post_id'=>YOUR_POST_ID_HERE
);
$comments_query = new WP_Comment_Query( $args ); 
$comments = $comments_query->comments;

您可以在此处找到可传递给WP_comment_Query构造函数的相关参数列表: WP docs

,

这就是答案。 @SessionCookieMonster说的对,应该将post_id添加到a​​rgs数组中,并且我应该使用get_the_ID(),这是正确的,但是,我不需要在循环中使用它,而只是将其分配为post_id

的值
$args = array(
    'status' => 'approve','post_id'=> get_the_ID()
);

$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...