Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

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.