Display the comment count using a shortcode

Adding this snippet to the functions.php of your wordpress theme will let you display the comment count for any post by simply using this shortcode [comments id="23" ] replacing the ID with the post ID you want to display the count for.

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" ]

Comments  Leave a Reply

  1. 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!