Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Created March 20, 2013 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jchristopher/5206136 to your computer and use it in GitHub Desktop.
Save jchristopher/5206136 to your computer and use it in GitHub Desktop.
In an ideal world I'd love to be able to 'nest' meta_query arguments in WP_Query, but I realize the limitation in the structure of this gist being too loose to implement programmatically, but I'd like to think about ways to possibly accomplish something like this in a more efficient way than filtering posts_join
<?php
/**
* My events have two Custom Fields, one for a start date and one for an end
* date. Start dates are required, but end dates are optional. That's because
* some events are one day only, while others might span multiple dates
* (e.g. conferences). Dates are stored in MySQL format.
*
* I want to pull events that meet these criteria:
* - Event has only a start date, and it's after NOW()
* - Event has a date range with an end date after NOW()
*
* That way, if a conference is currently going on (started previously but ends
* in the future) the listing doesn't go away.
*/
$args = array(
'nopaging' => true,
'post_type' => 'my_event',
'meta_query' => array(
// we want any of these 'conditions' to be met
'relation' => 'OR',
// 'condition' 1: has only a start date, and it's valid
array(
'relation' => 'AND',
// start date isn't empty
array(
'key' => 'event_start_date',
'compare' => 'EXISTS',
),
// start date is after NOW()
array(
'key' => 'event_start_date',
'value' => current_time( 'mysql' ),
'compare' => '>=',
'type' => 'DATE',
),
),
// 'condition' 2
array(
'relation' => 'AND',
// start date isn't empty
array(
'key' => 'event_start_date',
'compare' => 'EXISTS',
),
// end date isn't empty
array(
'key' => 'event_end_date',
'compare' => 'EXISTS',
),
// end date is after NOW()
array(
'key' => 'event_end_date',
'value' => current_time( 'mysql' ),
'compare' => '>=',
'type' => 'DATE',
),
),
),
);
$events = new WP_Query( $args );
@sc0ttkclark
Copy link

Just added this to Pods 2.3 (nested relations, as many levels deep as you need):

https://github.com/pods-framework/pods/blob/2.x/classes/PodsData.php#L2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment