Count posts or custom post types from last 24 hours (or from today)

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:

Read More
<?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)

Related posts

1 comment

  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(); ?>
    

Comments are closed.