WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I get the posts count for eg the last 4 days, but only for specific categories eg. (1,2,3)?

Thanks in advance.

share|improve this question
function get_days_ago_post_count_by_categories($ids){

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

    $args = array(
                    'post_type' => 'post',
                    'category__in' => (array)$ids,
                    'date_query' => $date_query,
                    'no_found_rows' => true,
                    'suppress_filters' => true,
                    '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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.