mysql query for category and date

How can I query the wordpress database so that I’m only display the number of posts from a certain category starting at a certain date?

I’ve tried something like this but it doesn’t work:

Read More
<?php
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts WHERE term_id = '4' AND post_date >= '2014-01-01 00:00:00' " );
echo "<p>User count is {$user_count}</p>";
?>

What am I doing wrong?

Related posts

1 comment

  1. Use wordpress native WP-Query:

    $args = array(
       'post_type'     => 'post',
       'date_query'    => array(
            'year '      => 2015,
       ),
       'cat'           => 5,
       'posts_per_page'=> -1
    );
    $query = new WP_Query( $args );
    $numberOfPosts = $query->post_count;
    

    $numberOfPosts should hold the number you are looking for. Just paste this where you used your original code which you’ve shared with us.

    Read more here: https://codex.wordpress.org/Class_Reference/WP_Query

    Excerpt from the above mentioned url:

    posts_per_page (int) – number of post to show per page (available with Version 2.1, replaced showposts parameter). Use ‘posts_per_page’=>-1 to show all posts (the ‘offset’ parameter is ignored with a -1 value). Set the ‘paged’ parameter if pagination is off after using this parameter. Note: if the query is in a feed, wordpress overwrites this parameter with the stored ‘posts_per_rss’ option. To reimpose the limit, try using the ‘post_limits’ filter, or filter ‘pre_option_posts_per_rss’ and return -1

    You can find a bunch of other options there aswell to tweak your query, to get the desired result. This should give the result you want for now.

Comments are closed.