Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

(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?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

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

global $withcomments; $withcomments = true;
share|improve this answer
    
Perfect. This is exactly what I needed. Thanks so much. –  Rodrigo Oct 26 '10 at 16:12
    
You are welcome! –  sorich87 Oct 26 '10 at 17:17
add comment

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; ?>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.