Display the Total Number of WordPress Posts, Comments, and Categories
Would you like to display the total number of posts, comments, and categories for your WordPress-powered website? You can do it the easy way using my free WordPress plugin, Simple Blog Stats. Or you can display your statistics directly, by querying the WordPress database. Here is the code that can make it happen.
Get number of posts, comments, and categories
Here is one way to query the WordPress database to get some basic count information. This can be used anywhere in your theme template, like sidebar.php
or even better tucked neatly inside of a custom function (added via functions.php
or plugin). The following code snippet is kept basic and should be self-explanatory:
<?php
$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");
if (0 < $numposts) $numposts = number_format($numposts);
$numcomms = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");
if (0 < $numcomms) $numcomms = number_format($numcomms);
$numcats = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->categories");
if (0 < $numcats) $numcats = number_format($numcats);
?>
<p><?php printf(__('There are currently %1$s <a href="%2$s" title="Posts">posts</a> and %3$s <a href="%4$s" title="Comments">comments</a>, contained within %5$s <a href="%6$s" title="categories">categories</a>.'), $numposts, 'edit.php', $numcomms, 'edit-comments.php', $numcats, 'categories.php'); ?></p>
As another example, here is a slightly modified version of the code, customized for use here at Perishable Press:
<?php
$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");
if (0 < $numposts) $numposts = number_format($numposts);
$numcomms = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");
if (0 < $numcomms) $numcomms = number_format($numcomms);
$numcats = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->categories");
if (0 < $numcats) $numcats = number_format($numcats);
?>
<?php echo $numposts . ' posts and ' . $numcomms . ' comments in ' . $numcats . ' categories'; ?>
Any questions? Hit me in the comments below! :)
2 responses to “Display the Total Number of WordPress Posts, Comments, and Categories”
Thanks for this info, just what I was looking for. I’m glad that I didn’t have to use yet another plugin to accomplish this. :)
My pleasure, don! Thanks for the positive feedback :)