Thursday, October 31, 2013

A look into: WordPress Date Query

We can display posts published on specific dates with the date parameters in WP_Query. The functionality, however, is basic. We can query posts by day, year, and month, but we were not able to query posts within a certain timeframe. Having been a victim once, I used a hack.

However (thanks to Alex Millis who contributed the code), in version 3.7, released recently, WordPress included Advanced Date Query which allows us to display more complex date-based post queries natively with WP_Query. With this, we can display posts that are published before or after certain hours. Let’s have a look at it.

Advanced Date Query

Version 3.7 introduced a new parameter called date_query. How do you use it?

Say, you are working on a news site, and want to highlight the news (or posts) from the previous week. By using date_query, we can write like so:


  $last_week_news = new WP_Query( array(
  	'date_query' => array(
  		array(
  			'after' => '1 week ago',
  			),
  		),
  		'posts_per_page' => 5,
  	));
  $query = new WP_Query( $last_week_news );
  

We can also display posts in a very specific timeframe. Below is an example of how we display posts between 15 December 2012 and 15 January 2013. This helps feature end of the year to the turn of the new year stories.


  $new_year_stories = new WP_Query( array(
  	'date_query' => array(
  		array(
  			'after'	=> 'December 15th, 2012',
  			'before' => 'January 15th, 2013',
  		),
  	),
  	'posts_per_page' => 5,
  ));
  $query = new WP_Query( $new_year_stories );
  

And, as mentioned, we can also display posts that were published in certain hours.

If your news website need to feature morning newsbits, you can write the code with date_query this way.


  $morning_news = array(
  	'date_query' => array(
  		array(
  			'hour'      => 6,
  			'compare'   => '>=',
  		),
  		array(
  			'hour'      => 9,
  			'compare'   => '<=',
  		),
  	),
  	'posts_per_page' => 10,
  );
  $query = new WP_Query( $morning_news );
  

It’s simpler, straightforward, and the code is more readable.

Final Thought

With the addition of advanced date query, WP_Query has become even more extensive. If keeping track of dates is important on your site e.g. if you are an event organizer or host multiple conferences or conventions, this new feature will definitely be very helpful.

For further reference, you can head over to the WordPress Codex page for Date Parameters.

No comments:

Post a Comment