Display the Comment Count Using a Shortcode

Snippets by IsItWP

Are you looking for a way to display the comment count for your posts? While there’s probably a plugin for this, we have created a quick code snippet that you can use to display the comment count using a shortcode.


All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

function comments_shortcode($atts) {
	extract( shortcode_atts( array(
		'id' => ''
	), $atts ) );

	$num = 0;
	$post_id = $id;
	$queried_post = get_post($post_id);
	$cc = $queried_post->comment_count;
		if( $cc == $num || $cc > 1 ) : $cc = $cc.' Comments';
		else : $cc = $cc.' Comment';
	$permalink = get_permalink($post_id);

	return '<a href="'. $permalink . '" class="comments_link">' . $cc . '</a>';

add_shortcode('comments', 'comments_shortcode');
[comments id="23" ]

In the above code, [comments id="23" ] is the shortcode that you can use to display the comment count by replacing the post ID in the shortcode.

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 46 biggest brands in the world using WordPress actively and 30 ways to make money online blogging.

Comments   Leave a Reply

  1. hi…
    thanks for your code.
    if i want to show comment content what to do?
    i want to show all commnet in “postid=20334” in my site within diffrent pages.
    plese help me.

  2. where exactly do i add this code in the functions.php`?

    1. Hi Alex, the location within the functions.php does not matter.

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!