Take the 2-minute tour ×

I am trying to echo the number of posts for the current month from all categories but it isnt working.

$month = date('m');
$year = date('Y');
$countposts = get_posts('post_type=post&year=' . $year . '&monthnum=' . $month . '&cat=3');
echo 'New posts '  . count($countposts);

category 3 is a parent category and has many sub categories. No matter what I do, it returns the value 5. I have published 30 posts for this month to test it but it doesnt count them. :(

What Im I doing wrong?

Update I have tried the following query and returns the same outpout

$current_year = date('Y');
$current_month = date('m');
$args = array(
    'cat'      => 3,
    'year'     => $current_year,
    'monthnum' => $current_month,
    'post_status'     => 'publish',
    'post_type'       => 'post'
$number_posts = get_posts( $args );
echo 'New posts '  . count($number_posts);
share|improve this question
Try using this : $month = date('n'); –  Vinod Dalvi Feb 27 '13 at 13:04
Hi thanks, same output, I even tried F, M, n, m –  Jose David Garcia Llanos Feb 27 '13 at 13:11

2 Answers 2

This is because the paramenter posts_per_page of the get_posts() function defaults to 5. Set it to -1 in your $args.

share|improve this answer

I wouldn't use get_posts function to count posts.

It will select these posts and it can be a lot of data that you will transfer/read from database and you won't use.

The other problem is that get_posts is very complex function. Just take a look at get_posts implementation in wp-includes/query.php file and check how many operations it does. So it's not very efficient solution for counting posts.

So instead I would use custom SQL query. It will be much more efficient. You can use this function:

function my_count_posts_from_month($year, $month) {
    global $wpdb;

    $query = "SELECT count(ID) FROM {$wpdb->posts} WHERE post_type='post' AND post_status='publish' AND YEAR(post_date)=%d AND MONTH(post_date)=%d";    

    return $wpdb->get_var( $wpdb->prepare( $query ), $year, $month );
share|improve this answer
Note that with 'fields' => 'ids' it is pretty light on SQL and data. It is much easier to deal with query API in the long run than raw SQL. –  Rarst Jun 21 '13 at 21:34

Your Answer


