Opened 12 months ago
Last modified 12 months ago
#59351 new enhancement
Add support for querying by an exact date with WP_Date_Query
Reported by: | sean212 | Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | normal | Version: | |
Component: | Query | Keywords: | |
Focuses: | Cc: |
Description
WP_Date_Query lacks the ability to query for posts with a specific date. Currently, to query for a post with a specific date string you would need to break it down to multiple arguments:
<?php $date = strtotime( '2023-08-13 20:12:50' ); $posts = new WP_Query( [ 'date_query' => [ 'year' => date( 'Y', $date ), 'month' => date( 'm', $date ), 'day' => date( 'd', $date ), 'hour' => date( 'H', $date ), 'minute' => date( 'i', $date ), 'second' => date( 's', $date ), ], ] );
There is no argument on WP_Date_Query that accepts a strtotime()
-compatible string for an exact date match. One workaround is to use a combination of before/after to get a simplified query.
Adding support for an exact match can be used when querying for posts from a specific date as well as including/excluding posts from a specific date for a complex query. Suggested syntax:
// Query for posts after January 1st, 2013 OR exactly on November 7th, 2010 [ 'date_query' => [ 'relation' => 'OR', [ 'after' => 'January 1st, 2013', ], [ 'exact' => 'November 7th, 2010', ], ], ]
Relates to #18694.
Note: See
TracTickets for help on using
tickets.
From my perspective, the challenge will be to build the WHERE clause depending on the input.
To stay with your example of
November 7th, 2010
, it should include all posts on that day and not justNovember 7th, 2010 00:00:00
orNovember 7th, 2010 23:59:59
? Another example:November 7th, 2010 18:00
as input should include all possible seconds?Right?
This is different from the
before
andafter
behavior, where the statement is filled up to a minimum or maximum, depending on theinclusive
parameter.strtotime / date_create, will always add year, month, day, hour,minute, seconds if they are missing.
From my perspective it's hard to determine if the hours, minute and seconds have been submitted by the user or by strtotime/date_create when using a string as input.
date_create is always called after trying to parse some common date formats has failed.
.
Does anyone have a idea, how to solve this?
This is working btw:
Maybe it would be nice to have
exact
but only with array as parameter? This would still require a lot validation.