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.
Instructions:
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'; endif; $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.
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.
thanks
You may want to try this code from the answer here: https://wordpress.stackexchange.com/questions/38753/how-to-get-comments-by-post-id
where exactly do i add this code in the functions.php`?
Hi Alex, the location within the functions.php does not matter.