WordPress Code to Get Total Number of Posts and Comments

Here’s a quick WordPress code to get and display the total number of posts and comments in your blog and we will even register it as a shortcode so that you can use the code anywhere within your posts or widgets.

This is quite useful if you wish to showcase how many published articles and comments are there in your blog. For example, you can use it on your blog’s landing page where you invite your readers to subscribe. With some CSS, you can even add it to your header just beside your logo. Boasting? Not really. It’s simply fun.

Displaying total posts and comments with shortcode

Fire up your functions.php file and add the following codes. The explanation is given below.

/** Shortcode for total number of posts and comments  - By WpSpells.com**/
function total_posts_comments(){  
global $wpdb;  //IMPORTANT to prevent Object error
$totalposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");
if (0 < $totalposts) $totalposts = number_format($totalposts); $totalcomments = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");
if (0 < $totalcomments) $totalcomments = number_format($totalcomments);

$output = "There are ".$totalposts." spells and ".$totalcomments." comments on WPSpells.com";
    return $output;   
}
add_shortcode('totalpostsandcomments', 'total_posts_comments');

You can now use the shortcode [totalpostsandcomments] anywhere in your posts, pages and widgets to show how many posts and comments are there on your blog.

Explanation

The code for the actual posts count is below:

$totalposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");
if (0 < $totalposts) $totalposts = number_format($totalposts);

And the one for counting the total comments:

$totalcomments = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");
if (0 < $totalcomments) $totalcomments = number_format($totalcomments);

Note that we declared $wpdb as global to prevent non object error. However this might differ in some themes or depending where you are using the codes. If you have previously declared the variable in the same function you are using these codes, you do not have to re-declare it.

Hope this post was useful.

Divi WordPress Theme

Leave a Reply

Be the First to Comment!

Leave a Reply


wpDiscuz