How to Query Posts by Date in WordPress Easily
To query posts by date in WordPress, use the
WP_Query class with the date_query parameter. This lets you filter posts by year, month, day, or a date range easily.Syntax
The date_query parameter in WP_Query accepts an array of conditions to filter posts by date. You can specify year, month, day, or use comparison operators like after, before, and inclusive.
Each condition is an associative array inside the date_query array.
php
new WP_Query([ 'date_query' => [ [ 'year' => 2023, 'month' => 6, 'day' => 15 ] ] ]);
Example
This example queries posts published on June 15, 2023, and displays their titles.
php
<?php $query = new WP_Query([ 'date_query' => [ [ 'year' => 2023, 'month' => 6, 'day' => 15 ] ], 'posts_per_page' => 5 ]); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); echo '<h2>' . get_the_title() . '</h2>'; } } else { echo 'No posts found for this date.'; } wp_reset_postdata(); ?>
Output
<h2>Post Title 1</h2>
<h2>Post Title 2</h2>
Common Pitfalls
- Not using
wp_reset_postdata()after a custom query can break other loops. - Forgetting to wrap
date_queryconditions inside an array causes errors. - Using string dates without proper format or comparison keys can lead to unexpected results.
php
<?php // Wrong: date_query not wrapped in array of arrays $query = new WP_Query([ 'date_query' => [ 'year' => 2023 ] ]); // Right: date_query wrapped in array of arrays $query = new WP_Query([ 'date_query' => [ [ 'year' => 2023 ] ] ]);
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| year | Filter posts by year | 'year' => 2023 |
| month | Filter posts by month number (1-12) | 'month' => 6 |
| day | Filter posts by day of the month | 'day' => 15 |
| after | Get posts after a date | 'after' => '2023-01-01' |
| before | Get posts before a date | 'before' => '2023-12-31' |
| inclusive | Include the boundary dates in after/before | 'inclusive' => true |
Key Takeaways
Use WP_Query with the date_query parameter to filter posts by date.
Wrap date conditions inside an array of arrays for correct syntax.
Always call wp_reset_postdata() after custom queries to avoid conflicts.
You can filter by year, month, day, or use after/before for ranges.
Set inclusive to true to include boundary dates in your query.