0

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

<?php
$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

    <?php
wp_reset_postdata();
$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);
?>
1
  • Try using this : $month = date('n'); Feb 27, 2013 at 13:04

2 Answers 2

2

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

1

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 ));
}
3
  • 2
    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, 2013 at 21:34
  • @Rarst and yet, if there will be 100k posts, then you'll have to SELECT 100k IDs instead of getting only the count from DB. But I totally agree that using get_posts is easier to deal with later on. Jun 26, 2018 at 10:41
  • @Rarst Can you elaborate on this approach?
    – Adeerlike
    Jan 23, 2023 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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