0

我正在构建一个自定义 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.';
}
?>

4

2 回答 2

1

为了只显示特定帖子 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

于 2020-09-22T03:51:15.817 回答
0

这就是答案。post_id@SessionCookieMonster的说法是正确的,应该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 );
于 2020-09-22T15:57:43.387 回答