How to show the comment count for a certain WordPress post using a shortcode

Just add this WordPress Code Snippet to the functions.php file in your current WordPress theme in order to show the comment count for a certain WordPress post using a shortcode.

/**
 * Get post comment count using shortcode
 *
 * @author WPSnacks.com
 * @link http://www.wpsnacks.com
 */
function comment_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';
		endif;
	$permalink = get_permalink($post_id);

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

}
add_shortcode('comments', 'comment_shortcode');

Then just use this shortcode in your content to display the comment count for a certain post:

[comments id=”20″]

Replace the 20 above with the ID of the post you want to show the comment count from.

   Related Sponsored Links

Disclaimer: The information contained in this website is for general information purposes only and in no event will this site or its owners be liable for any losses or damages associated with your use of our site or content. Click here to see our full Disclaimer.

Leave a Comment

*