How to get the post count for the last x days filtering by categories

function get_days_ago_post_count_by_categories($ids){

    $date_query = array(
                        array(
                            'after'=>'4 days ago',
                            'inclusive' => true,
                            )
                        );


    $args = array(
                    'post_type' => 'post',
                    'post_status'=>'publish',
                    'category__in' => (array)$ids,
                    'date_query' => $date_query,
                    'no_found_rows' => true,
                    'suppress_filters' => true,
                    'fields'=>'ids',
                    'posts_per_page'=>-1,
                    'orderby' => 'ID'
                );

    $query = new WP_Query( $args );

    return $query->post_count;
}

Note: code isn’t tested and just to show you how to achieve it with WP_Query

WP_Query introduces date_query since 3.7.


As you can see, I add some extra WP_Query arguments and their purpose are to generate most optimized SQL for performance sake. However, the generated SQL will still be SELECT ID.

In fact, I would suggest that you use the row SQL with $wpdb->get_var. You know, SQL “aggregate” function (SELECT COUNT(ID) in your case) takes less resource than "SELECT ID".

You can find the WP_Query generated SQL by outputting $query->request.

Leave a Comment