Question

(Moderator's note: The original title was "Is there a way to get post comments by post ID on a custom loop using WP-Query()?")

Hi! I'm running a custom loop using WP_Query, that only displays one post from a specific category on the home.php page, like so:

<?php $pr_q = "cat=11&posts_per_page=1"; $pregunta_q = new WP_Query($pr_q); ?>
<?php while ($pregunta_q->have_posts()) : $pregunta_q->the_post(); ?>
    <!-- post stuff here -->
<?php endwhile; ?>

Is there any way to have it show comments for that specific post? I tried including the comments template inside the loop and nothing. Is there a function that loads the comments for a specific post that I can use inside home.php or anywhere else?

Was it helpful?

Solution

To be able to use the comments template in your loops, add

global $withcomments; $withcomments = true;

OTHER TIPS

By default, WP_Query will only load comments WITH THE QUERY if you're

  1. looking at a comments feed, or
  2. looking at a singular item.

Your query wouldn't automatically pull in the comments because, as a category listing (even though there's only one) it doesn't count as 'singular'. Fortunately, there's a way around this. Basically, before you pull in the comments template, you should fetch the comments and put them into the query object you're using:

<?php $pr_q = "cat=11&posts_per_page=1"; $pregunta_q = new WP_Query($pr_q); ?>
<?php while ($pregunta_q->have_posts()) : $pregunta_q->the_post(); ?>
  <!-- post stuff before comments here -->
  $comments = get_comments( array(
    'post_id' => $post->ID,
    'orderby' => 'comment_date_gmt',
    'status' => 'approve',
  ) );
  if(!empty($comments)){
    $pregunta_q->comments = $comments;
    $pregunta_q->comment_count = count($comments);
  }
  <!-- comment stuff here -->
<?php endwhile; ?>

John P Bloch answer is correct. Comment only will load if you are on singular & on comment feed. Fortunately we can override this behavior by adding additional parameter on WP Query.

'withcomments' => 1, 'feed' => 1

No need for WP_Query or custom loop for comments. You can just get post comments in post custom loop or post WP_Query . In loop you have the post_id. Use post_id to get comments. Code is written below.

$comments = get_comments('post_id='.$post->ID);
       foreach($comments as $comment) :
               print_r($comment);
       endforeach;
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top