WordPress: display the number of comments outside the Loop

WordPress: display the number of comments outside the Loop

How to get the comment count and display it outside the WordPress Loop.

WordPress provides several functions to display the number of comments associated to each post. Unfortunately, most of these functions work only inside the Loop. In this article we'll see how to get the comment's number outside the Loop.

We need to query the database two times, one to get the comment count and another one to know if the comments associated with the current post are still open. Then we have to check if the current post is not a page.

We can add the following code to our functions.php file

function add_comment_count_to_posts($content) {

	global $post;
	global $wpdb;
	
	$id = $post->ID;
	
	$comment_count = $wpdb->get_var("SELECT comment_count FROM $wpdb->posts WHERE post_status = 'publish' AND ID = $id");
	$comment_status = $wpdb->get_var("SELECT comment_status FROM $wpdb->posts WHERE ID = $id");
	
	$html = '<div class="comment-popup">';
	$html .= '<span>';
	$count = '';
	
	if($comment_status == 'open') {
	
		$count = $comment_count;
	
	
	} else {
	
		$count = 'Off';
	
	}
	
	$html .= $count . '</span></div>';
	
	if(!is_page()) {
	
		return $content . $html;
		
	} else {
	
		return $content;
	
	}
	

}

add_filter('the_content', 'add_comment_count_to_posts');