I have a query as follows:
$wp_query = new WP_Query( 'meta_key' => 'end_date', 'meta_value' => 'today', 'meta_compare' => '>=', 'post_type' => 'vehicle' );
I want to show only those posts of the vehicle post type that have the meta key end_date which contains a date that is later than today’s date.
How can this be accomplished?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
First, your date format has to be in descending order from largest to smallest units, i.e.: year, month, day, hour, minute, second, etc., otherwise MySQL can’t query or order on the field. In this example I use year – month – day:
$today = date( 'Y-m-d' );
$args = array(
'post_type' => 'vehicle',
'meta_query' => array(
array(
'key' => 'end_date',
'value' => $today,
'compare' => '>=',
'type' => 'DATE'
)
)
):
$query = new WP_Query( $args );
Method 2
WordPress added Date Queries in 3.7. So you could always try:
$today = date( 'Y-m-d' );
$args = array(
'post_type' => 'vehicle',
'date_query' => array(
//set date ranges with strings!
'after' => 'today',
//allow exact matches to be returned
'inclusive' => true,
),
);
$query = new WP_Query( $args );
More on this can be found at https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0