Home / comment / Display the comment count using a shortcode
  • How to Display the comment count using a shortcode

    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.

    wordpress snippet : PHP

    <>
    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';
    		endif;
    	$permalink = get_permalink($post_id);
    	return '<a href="'. $permalink . '" class="comments_link">' . $cc . '</a>';
    }
    add_shortcode('comments', 'comments_shortcode');
    

    wordpress snippet : SHORTCODE

    <>
    [comments id="23" ]
    

    ( WordPress codex functions, hooks, in this snippet. )

    get_permalink, get_post, add_shortcode, shortcode_atts,
  • Alex

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

    • http://wpsnipp.com Kevin Chard

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