0

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

Jeff S
  • 109
  • 2
  • 13

2 Answers2

1

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

  • this makes sense but how do I populate the id dynamically? I can't seem to find the answer to this and the examples I do find have hard coded id's. I'll check the docs again, but I've been through already a few times – Jeff S Sep 22 '20 at 04:05
  • 1
    Inside the loop you could do something like `get_the_ID();` – SessionCookieMonster Sep 22 '20 at 12:21
0

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 );
Jeff S
  • 109
  • 2
  • 13