How to fetch all posts in a category that were published between two given dates?

There are two ways to do this, both involve WP_Query.

  1. No Hooks

    Unfortunately, this is the less flexible way of doing things, but it is the way which is built into WP_Query. With the default WP_Query time parameters, you can get all the posts for a given numerical date. For example, all the posts from 2011, or all the posts from the 3rd month, or all the posts from this calendar week, etc. You can also do permutations thereof (so all the posts from the 3rd month of 2011). Unfortunately, this can leave a lot to be desired.

  2. Hooks

    With the posts_where hook, it is possible to filter by post_date. You will need to write the SQL you want to ADD (and I stress, ADD) to the WHERE portion of the query by hand, so for example:

    wpse51235_posts_where( $where ) {
        $where .= ' AND post_date < blah AND post_date > blah2 ';
        return $where;
    }
    

    Note that it opens and closes with a ‘ ‘, in addition to opening with an AND. This is to ensure that if some other code doesn’t open with a space, the whole query will not break. There’s no way to have too many spaces.

tech