Exploring WordPress Date Queries for Post Filtering
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
. This enhancement enables displaying posts published before or after specific hours. Let’s dive deeper into this feature.
Utilizing Advanced Date Queries
With version 3.7, a new parameter called date_query
was introduced. How do we utilize this new feature?
Imagine you’re managing a news site and aim to feature articles from the previous week. By leveraging date_query
, you can easily achieve this as shown below:
$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 );
Featuring Posts Within Specific Timeframes. Below is how you can showcase posts from 15 December 2012 to 15 January 2013, perfect for highlighting end-of-year and New Year narratives.
$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 );
This feature is not limited to dates; it also allows for the display of posts published at specific hours.
For instance, to highlight morning news on your site, you can configure date_query
as follows:
$morning_news = array( 'date_query' => array( array( 'hour' => 6, 'compare' => '>=', ), array( 'hour' => 9, 'compare' => '<=', ), ), 'posts_per_page' => 10, ); $query = new WP_Query( $morning_news );
This approach is simple, direct, and enhances code readability.
Concluding Remarks
With the introduction of advanced date query capabilities, WP_Query
has expanded its utility. This feature is invaluable for sites where date tracking is crucial, such as for event organizers or conference hosts. It offers a powerful tool for managing content visibility based on time parameters.
For additional information, please visit the WordPress Codex page on Date Parameters.
Note: This post was first published on the Oct 31, 2013.