4

I’m having some difficulties trying to get total number of comments from posts within a specific custom taxonomy.

The setup is as such: I’ve created a custom taxonomy for my posts, called “features”. Within that taxonomy I’ve like four or five terms. Then, some of my posts are put into feature-term 1, feature-term 2, etc.

I can get this to work and when making a query I can also retrieve how many posts are in each term. But then I would like to show the total number of comments that all the posts within each feature-term has. So for example, under feature-term 1, the total number of posts is 12 and the total number of comments are 34.

I’ve tried with this query:
SELECT SUM(comment_count) AS totalcc FROM wp_posts, wp_term_relationships WHERE wp_term_relationships.term_taxonomy_id = {$term->term_id} AND object_id = ID
But it gives me an incorrect answer can I can’t quite get an overview of where I’m failing.

Maybe there is an easier way to do it, a way that Wordpress provide but if so I haven’t been able to locate that.

Any help or suggestions would be appreciated.

Sincere
- Mestika

1 Answer 1

1

You'll need to loop through your posts, use get_comments_number() to get the number of comments for each post, and then accumulate the total number of comments in a separate variable. e.g.:

<?php
$features_comment_count = 0;

if ( have_posts() ) : while ( have_posts() ) : the_post();

$features_comment_count += get_comments_number();

endwhile; endif;
?>

(I'll assume that you know how to custom-query your posts, and can adapt the above code as necessary.)

If you want to count the comments before outputting post content, then simply run the above loop, and then rewind posts using rewind_posts():

<?php rewind_posts(); ?>

Then, you can output your posts loop as per normal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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