1

I'm trying to count the number of live comments on each post. I would like to extract them on a custom page like http://example.com/count.php and have them output like this:

http://example.com/the-post-url-with-3-comments/    3
http://example.com/the-post-url-with-no-comments/   0
http://example.com/the-post-url-with-12-comments/   12

The spacing between all the posts don't matter quite as much, I just need the two columns with all my posts and number of approved comments.

I have come close to doing this with this post and using echo get_comment_count( 149 ); but it only uses one post at a time. I would like to extract all the posts.

Thanks for your help.

0

This is pretty easy to do. Put this code in your functions.php file.

The logic is pretty straightforward.

  • Get all posts with get_posts().
  • Iterate over all post, extract comments count and permalink of current post and
  • Print out the results.

.

add_action( 'init', 'get_comments_count' ); // Hook to init, elsewhere or use directly in your code
function get_comments_count() {

  $all_posts = get_posts( array( 'numberposts' => -1 ) );

  foreach( $all_posts as $current_post ){

    $comments_count = get_comment_count( $current_post->ID );
    $permalink = get_permalink( $current_post->ID );

    printf( '<a href="%s">%s</a> - %s<br>', $permalink, $permalink, $comments_count['total_comments'] );

  }
}
0

Try below code. It will display comment count of each post in post loop. It also provide link to comments.

<a href="<?php comments_link(); ?>"><?php comments_number('0 Comment', '1 Comment', '% Comments'); ?>
</a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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