DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

One of my readers, fromtheold, asked me how he can display how many post have been published today on his blog, just as the popular blog Lifehacker. Here’s how to do it.

For this recipe, we’ll have to mix two recipe I posted here this week. The first one is How to: Display today’s posts and the second is How to: Display the total number of posts on your WordPress blog.

The first thing to do is to get today’s date, and then create another variable containing today’s date – 24 hours. Then, we just have to send a SQL request to the database by using the $wpdb->get_var() method.

<?php
$today = date("Y-m-d H:i:s"); //Today's date
$daysago = date("Y-m-d H:i:s",strtotime(date('Y-m-j H:i:s')) - (1 * 24 * 60 * 60));  //Today - 1 day

$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_date BETWEEN '$daysago' AND '$today'");

if ($numposts >0) {
    echo $numposts.' posts published today';
} else {
    echo "No posts published today";
?>

2 Comments

  1. (I can’t tell if my comment went through yesterday; if it did, I’m sorry for this repeat)

    I can’t, for the life of me, figure out how to use this code snippet. I assume I just copy’n’paste this into the functions.php file (I prefer to use the Code Snippets plugin), but then what? How do I get it to show where I want to – in the header area?

    I’m using the Thesis theme, and a plugin that adds widgets to the header. Can I make the Today’s Posts snippet into a widget? Is there a simple way to do that?

    I am a complete PHP noob, so I don’t know how to fix this for myself.

  2. Will it be faster if you use > instead of between comparison?

    $numposts = $wpdb->get_var(“SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = ‘publish’ AND post_date > ‘$daysago’ “);

Leave a Comment

Your email address will not be published. Required fields are marked *