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.

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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