Posted on July 2, 2013 by Curtis McHale

Getting WordPress posts based on date ranges

Today we’re going to continue with our work on the WPTT ICS Feeds plugin. Currently we are just getting every post in the database. That’s a super expensive option if you have lots of posts.

Today we’re going to modify the plugin so that we are only getting posts 6 weeks ago or sooner and all future posts.


To be able to get posts only 6 weeks old we need to turn to the posts_where filter. WP_Query can do a bunch of date based things for us, but it can’t get posts older than today by a set range. I could get us posts from a month ago, but not based on today.

posts_where passed through 1 variable which is the current $where filter running. All we need to do is return a date based $where value.

First we need to add and remove our filter around our WP_Query object in our generate_feeds function.

add_filter( 'posts_where', array( $this, 'two_months' ) );

$feed = new WP_Query( $args );

remove_filter( 'posts_where', array( $this, 'two_months' ) );

You can see that our posts_where filter is calling the two_months function. I’ll show you what two_months does in a second.

It’s important to note that we remove the filter right away. We only want this date based filter to run on our calendar feeds. If we didn’t remove it we would be limiting WP_Query any time it ran inside WordPress.


Now we can take a look at our two_months function. Add it just after our `generate_feed` function ends.

 * Adds a where clause to our posts so that we get 6 weeks back in time.
 * @since 1.2
 * @author WP Theme Tutorial, Curtis McHale
 * @access public
public function two_months( $where ){

  $how_old = apply_filters( 'wptt_ics_feeds_how_old', '-6 weeks' );

  $where .= " AND post_date > '" . date('Y-m-d', strtotime( $how_old )) . "'";
  return $where;

} // two_months

Here we see our $where variable passed in to the function. Then we create a variable called $how_old. I added a filter here called wptt_ics_feeds_how_old so that a theme/plugin developer can change how the value of $how_old without needing to ‘hack’ the plugin. By default $how_old is equal to -6 weeks.

Next we add to our $where variable and ask for posts where the post_date is greater than 6 weeks ago. To get 6 weeks old we use strtotime which takes english language and translates it in to a value PHP can understand.

Once we have asked for posts with a date greater than 6 weeks ago we return our $where variable.

That’s it. If we looked at our ICS feeds in the calendar now we’d only see posts that are less than 6 weeks older than today.

If you want some advanced reading on filters MySQL and WordPress there is a great article called Understanding MySQL in WordPress that you should read. It’s pretty technical so bookmark it and read it a few times. You’ll get a bit more each time you read it.