Counting Posts

Daniel at The Web Design Journal emailed me to ask about the post count block that appears in my sidebar. For example:

There are 2 posts in the last 30 days, and 323 total posts.

There are a number of ways to get the total post count. The last 30 days post count is a feature I wanted to add when I switched to WordPress and designed this theme. After searching for an existing solution, I ended up rolling my own. For reasons I don’t recall, I also wrote my own function for getting the total post count. I had meant to post it here, but had forgotten about it.

Instead of designing this as a WordPress plugin, I added it directly to template. In my sidebar template, I added the following:

<p>There are <?php echo get_post_count_inlast(30) ?> posts in the last 30 days, 
    and <?php echo get_post_count() ?> total posts.  
    <a class="sidelink" href="<?php echo get_bloginfo('wpurl')?>/archive/">Archives &raquo;</a></p>

The special bits here are the calls to get_post_count_inlast() and get_post_count(), which are simple PHP functions I wrote to query the WordPress MySQL database. I added these functions to functions.php in the theme directory for my theme. I’m not sure if all WordPress theme include this file, but the default theme, on which I based my theme, already provided this file. In this file, I added the code for the two new functions:

function get_post_count() {
    global $wpdb;
    return $wpdb->get_var('select count(*) from wp_posts where post_status = "publish"');

function get_post_count_inlast($days=30) {
    global $wpdb;
    return $wpdb->get_var("select count(*) from wp_posts where post_status = 'publish' and DATEDIFF(CURRENT_DATE, POST_DATE) <= $days");

I’m no PHP expert, I’ve picked up just enough to make the tweaks I wanted to my templates, but I believe you could even include the function definitions directly in the sidebar.php file, as long as they’re inside a <?php ... ?> tag.

Hope someone finds this useful. If you decide to add this to your site, please drop me a comment, and be sure to fill in your site URL.

(The source code in this post is released under the GNU GPL (just like WordPress), and comes with no warranty of any kind, express or implied.)