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.
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";
?>
11 Responses
Brilliant!!!! Thanks a lot for this tutorial. I have been struggling to do this for weeks
Glad it helped
It’s really easy). Nice explanation. You’ll get my vote on DZone!
Thank you, Flex! I’m glad you enjoyed this recipe and voted for it on Dzone!
Hey its nice recipe. helped me a lot. you are really doing a nice job.
on the last line there is missing a ;
so the correct code is
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.”;
?>
an other correction to your code
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.”;
}
?>
What’s if the blog is written by 2 or more bloggers and they are in the different time areas? Have you tried to test this script in this case?
Trackbacks: