I need to get posts pertaining to a given category, AND :
- have the event_start_date (custom field) greater or equal than today’s date
- OR have a event_end date (custom field) greater or equal than today (if their event_start_date date is less than today’s date
The results need to be order using the custom_start field.
I’m working on this code, but I cannot find the relevant documentation for this specific usecase. Can you help, either pointing me to a good online explanation, or explain me how to fix my query?
$since = date('Y-m-d');
$args = array(
'meta_key' => 'event_date_start_id',
'category_name' => 'private',
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_query' => array(
'relation' => 'OR',
array(
//event_date_start_id greater or equal to $since
'key' => 'bjab_event_date_start_id',
'value' => $since,
'type' => 'numeric',
'compare' => '>='
),
array(
//event_date_end_id greater or equal to $since
//and event_date_start_id lower than $since
// and event_date_start_id != ""
'relation' => 'AND',
array(
'key' => 'bjab_event_date_start_id',
'value' => $since,
'type' => 'numeric',
'compare' => '<'
),
array(
'key' => 'bjab_event_date_end_id',
'value' => $since,
'type' => 'numeric',
'compare' => '>='
),
array(
'key' => 'bjab_event_date_end_id',
'value' => '',
'type' => 'numeric',
'compare' => '!='
)
)
)
);
$query = new WP_Query( $args );
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
Since WordPress 4.1 it is possible to build nested meta, date and tax queries. I’ve not tested it but the code bellow should work. Also, I recommend to replace PHP date() function with current_time from WordPress to get the current date taking in account the blog time zone configuration:
After the chat with you, it seems that you just need to use “DATE” as type argument.
$since = current_time('Y-m-d');
$args = array(
'meta_key' => 'bjab_event_date_start_id',
'category_name' => 'private',
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_query' => array(
'relation' => 'OR',
array(
//event_date_start_id greater or equal to $since
'key' => 'bjab_event_date_start_id',
'value' => $since,
'type' => 'DATE',
'compare' => '>='
),
array(
'key' => 'bjab_event_date_end_id',
'value' => $since,
'type' => 'DATE',
'compare' => '>='
)
)
);
$query = new WP_Query( $args );
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