I would like to display count for custom post types (or posts) which was published that day (last 24 hours or TODAY).
I use this snippet to get count of all posts from “posts” or from “custom post types”
<?php
$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE (post_status = 'publish' AND post_type = 'post')");
if (0 < $numposts) $numposts = number_format($numposts);
?>
in templates:
<?php echo $numposts ?>
but I don’t know how to display count only for last 24 hours or TODAY (it means from midnight to midnight)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can write your own function (add it to functions.php file:
function get_posts_count_from_last_24h($post_type ='post') {
global $wpdb;
$numposts = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(ID) ".
"FROM {$wpdb->posts} ".
"WHERE ".
"post_status='publish' ".
"AND post_type= %s ".
"AND post_date> %s",
$post_type, date('Y-m-d H:i:s', strtotime('-24 hours'))
)
);
return $numposts;
}
function get_posts_count_from_today($post_type ='post') {
global $wpdb;
$numposts = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(ID) ".
"FROM {$wpdb->posts} ".
"WHERE post_status='publish' ".
"AND post_type= %s ".
"AND DATE_FORMAT(post_date, '%Y-%m-%d') = %s",
$post_type, date('Y-m-d', time())
)
);
return $numposts;
}
And then use it in template:
<?php echo get_posts_count_from_last_24h(); ?> <?php echo get_posts_count_from_today(); ?>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0