How to get comments count in post?

AI-generated summary

How to get comments count in post?

Vladislav_Musílek needs help displaying the number of comments on a post detail page in a custom Discourse template. angus suggests using the get_comments_number() function, which returns the total number of comments from both Wordpress and Discourse.

However, Vladislav_Musílek wants to combine existing comments from the site with Discourse comments. angus explains that get_comments_number() will work for a single post, but for a total site comment count, a custom function is needed. Angus provides an example function, count_all_comments(), which combines approved Wordpress comments and Discourse comments on published posts.

Hello,

I am linking a discourse with a custom template and I need to get the number of comments to display in the post detail.
Here I have the article - První auta od Xiaomi. Rychlejší umí jet hodně přes 200 km/h! and here is the corresponding discourse - První auta od Xiaomi. Rychlejší umí jet hodně přes 200 km/h! - Komentáře ke článkům - Komunita Svět Androida
How do I get the current number of comments?

Thank you for your help.

Hey there @Vladislav_Musílek,

The WP Discourse plugin hooks into the filter for the standard Wordpress function get_comments_number. So you can show the number of Discourse comments on a post by echoing that in your template:

echo get_comments_number();`

For more on WP Discourse comments check out

Hello,

thank you for your help, but problem is that there are comments left on the existing site and I need to get the number of existing comments, comments on Discourse and add them up. Is it possible to do this?

If you’re looking to get the total of Wordpress and Discourse comments for a single post, then get_comments_number() will work (i.e. it will return the sum of both).

If you’re looking to get a sum total of all comments on your site (not from a specific post), whether from Wordpress or Discourse, this is a somewhat subjective question. It depends what you mean by “all comments”. You’ll need to write a custom function for this, and would do if you were just counting Wordpress comments by themselves. You’d do something like this and use it in a shortcode or block

function count_all_comments() {
     $wordpress_count = wp_count_comments();
     $count = $wordpress_count->approved;
     $query_args = array(
      	'post_status' => 'publish',
     );
     $query = new WP_Query($query_args);
     if ( $query->have_posts() ) {
	    while( $query->have_posts() ) {
		  $query->the_post();
		  $count += intval( get_post_meta( get_the_ID(), 'discourse_comments_count', true ) );
        }
     }
    return $count;
}

(I just wrote this on the fly so please test it before you use it :slight_smile: )

Note that I’ve chosen to return the approved Wordpress comment count and the count of Discourse comments on published posts. There are other choices you could make there about what qualifies for your count.