Using WP_Query To Get Posts From Last Week

One of the most powerful aspects of the WordPress API is WP_Query as it allows us to retrieve a wide variety of content through a relatively simple interface.

That is, it allows us to retrieve complicated datasets ranging from custom post types, post status, date ranges, taxonomies, meta data, categories, and so on all with a relatively standard set of PHP constructs (mainly arrays) and with a really solid reference in the associated Codex article.

One of the nicest things about WP_Queryespecially since WordPress 3.7, are the advanced date query parameters that we can use in order to retrieve information from a specific date range without having to do a lot of complicated date math (which, of course, is every programmer’s favorite aspect of development).

If you learn how to use that particular aspect of WP_Query and you’re familiar with PHP’s strtotime function, then you can retrieve posts from a range of dates easily.

An Example: Get Posts From Last Week

Though this is not the most complicated example, it’s one that I’ve found to be all to common among various projects on which I’ve worked, and it shows off a couple of aspects of WP_Query and strtotime that may be helpful in future work.

Before actually looking at the code, let me clarify that I’m simply going to be retrieving all of the standard posts (that is, all of the posts with post_type = 'post' from the WordPress database) that have been published in the last week.

That’s it.

And for anyone who has worked with dates, your mind may immediately go into thinking: “Okay, so I’ll take today’s date, convert it to a certain format – perhaps UNIX microseconds – subtract seven days from it, convert that to UNIX microseconds, specify a date range, and then run the query.”

I don't want to lose my train of thought.

Or maybe not. I don’t know because I don’t know how flexible the systems you’ve worked with are as it relates to date management.

But here’s a gist of code that shows exactly how to do what I’ve mentioned without any of that complicated date math:

It’s almost too easy, isn’t it?

Don’t Sweat The Small Stuff. Except For Now.

Some people say not to sweat the small stuff, but there are a couple of things worth pointing out in the above query that I think are worth noting.

But if we have to sweat it, is it really small stuff? This isn’t a philosophy article, so I digress.

Anyway, so technically the above query would work if you left out the initial arguments of post_type, post_status‘, orderby, and order.

If you’re looking to retrieve only posts, then leaving out the post_type should be fine, that’s what the default value is; however, if you’re looking to write self-documentating code without someone having to double-check to Codex article to see what kind of information you’re retrieving, then I think it’s a good idea to specify it.

Secondly, post_status is important to specify because if you have posts that are scheduled for a future date but still fall within the past week, it will retrieve that data, as well. To that end, I always specify the publish post status because I only want publicly available, published articles.

As far as the dates are concerned, you can specify these or not. There are default values, but in keeping with the self-documenting code, I tend to show exactly what I’m doing.

And finally, the date_query – this is the most interested part of the code. There are a lot of options that you have as it relates to retrieving information over a specific date range which I’m not going to cover in this post (but be sure to read up on it!).

The key takeaway from this particular article is that the after argument (or the before argument, if you specify it) will be parsed by PHP’s strtotime function which means that you can use relative time strings to calculate time.

As in the example above, I’ve specified 1 week ago which means that any time this query is run, all posts from one week ago from the current time will be retrieved.

Kinda neat, right?

So let’s say that you want to get posts from last week and you want to do so, say, on a Saturday. Then running the above query on a Saturday will retrieve all of the posts that have been published since last Saturday.

Obviously, what I’m doing within the while loop is purely for demo purposes – you can do whatever you’d like – but it demonstrates the point.

“Math is Hard, Let’s Go Shopping!”

Anyway, if you have any interested in attempt to get posts from last week (or custom post types from any date range, really), then play around with WP_Query and the date_queryargument.

It’s pretty cool, and offers up a lot of really neat functionality without some of the hoops you generally have to go through when working with dates.

20 Comments

Excellent article on using date_query. I’ve followed along every since they were first proposed for 3.7, but cool to see a simple, practical use.

Playing around with your code and I realize that Sticky Posts are included. You can prevent this by adding 'post__not_in' => get_option( 'sticky_posts' ).

Thanks, great article! I like the way you write about wp stuff! Keep going!

really really useful! thank you for sharing

The code is missing from this article…

This is brutally genius . save me lot of time. :)
Thanks

Hi , great job Tom. thank.
It works for me for one parameter “after”..but if i want to compare between dates? . i tried this ( i send values by a form ( method get) )
$arg=array(
‘post_type’ => ‘post’,
‘paged’ => $paged,
‘posts_per_page’=>10,
‘date_query’ => array(
array(
‘after’ => $_GET[‘fromdate’],
‘before’ =>$_GET[‘todate’],
‘inclusive’ => true,
)
)

);
$the_query=new WP_Query($arg);

i tried to put manually dates too and i get any posts.. Please help!

Hi!

Great article thank you! You may have already answered this and I’ve missed it….

Within my custom posts I have a custom field that holds a string date, I would like to use the Wp_Query function to return only posts that are say from this month? Or also to order by those string dates?

Ive read a lot online about using a strtotime() function and well as lots of other ideas and Im frankly confused now! Would be great if you could post an example to help me and I’m really stuck! My custom post type is votes (which I can query fine), and the post_meta date I want to check is a string stored as: 2015-01-13 20:14:37

Really appreciate if you could help!

Gary

    It sounds like what you’re looking for is using the meta_query feature of WP_Query. You’re able to specify the meta_key and the meta_value and since you seem have both on hand, you don’t have to worry about using the strtotime function to get what you need.

    Hope this helps!

      Hi Tom, firstly really appreciate you getting back to me!

      Im just confused as to how WordPress will treat what I have as a date when it is a string in a different format?

      so I’m using a custom post type ‘votes’ and am using the Advanced Custom Fields plugin to add additional fields to store data, one of which is a date. The data is stored as a string (long text), this is stored in the format of ‘2015-01-09 16:48:37′.

      meta_key = ‘completion_date’

      I am wondering what to add to the following query to pull only posts which have a completion date of this current month and year, as well as a separate query to find posts which have a completion date within this year.

      And finally a way to order query posts by this string date?

      My starting Query I’m stuck at is:

      $args = array (

      ‘post_type’ => ‘votes’,

      ‘meta_query’ => array(

      array(

      ‘key’ => ‘status’,

      ‘value’ => ‘Completed’,

      ),

      ),

      );

      $query = new WP_Query( $args );

      Sorry for the big ask but everything I read confuses me more when I’m sure it is very simple!

      Really do appreciate the help and I hope I have provided enough information!

      Thanks

      Gary

        This is getting more complicated than can really be answered within the context of a blog comment, but based on what you’ve said, I think you’ll need something more advanced with WP_Query.

        Since you have dates stored as a timestamp, but you’re looking for records that have a a year as part of their substring and/or a month as part of their substring, then you’re technically looking for a LIKE SQL query.

        Using meta_compare may get you what you need, and since you’re querying off a factor of two things (month and year), you may need the relation clause as well. You can read more about that here in the Codex as it gives pretty good examples.

Leave a Reply

Name and email address are required. Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>