Wordpress: help getting correct comments to display on single post

1.2k views Asked by At

I'm building a custom Wordpress theme and on any single post ALL of the comments display instead of just the comments for that post. Obviously, I'm looking to display just the comments made on that post.

<?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.';
}
?>

I'm essentially using this code, that I got directly from 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.';
}
?>

2

There are 2 answers

2
SessionCookieMonster On

In order to only show the comments for a specific post ID, you have to pass a relevant post ID in the post_id argument, like:

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

You can find a list of relevant arguments that can be passed to the WP_comment_Query constructor here : WP docs

0
Jeff S On

This was the answer. @SessionCookieMonster was correct in saying should add the post_id into the args array and that I should use get_the_ID(), however, I didn't need to use that inside the loop, but rather just assign it as the value for post_id

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

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