Skip to content

Instantly share code, notes, and snippets.

Created Jan 3, 2019
What would you like to do?
* DPS Event Queries
* @see
function be_dps_event_query( $args, $atts ) {
// Only run on event queries
if( empty( $args['post_type'] ) || 'event' != $args['post_type'] )
return $args;
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = 'sc_event_date_time';
$args['order'] = 'ASC';
$meta_query = array(
'key' => 'sc_event_date_time',
'value' => time(),
'compare' => '>',
$args['meta_query'] = $meta_query;
return $args;
add_filter( 'display_posts_shortcode_args', 'be_dps_event_query', 10, 2 );

This comment has been minimized.

Copy link

@rjdusk rjdusk commented Aug 26, 2019

Hey @billerickson I've been playing with this function for the past hour and something suddenly dawned on me. Here you are checking the $arg['post_type'] but should it not be $atts['post_type'] ? The later worked for me when the former does not.

Also your $meta_query is an array inside an array. I changed this to just one array and everything works as desired.

I'll include my working code below. It's just checking a custom field called start_date on a custom post type called event and comparing if it is less than the current date. This is a previous events listing.

function be_dps_future_events($args, $atts)
  // Only run on event queries
  if ('event' != $atts['post_type'])
    return $args;

  $args['order'] = 'ASC';
  $args['orderby'] = 'meta_value';
  $args['meta_key'] = 'start_date';
  $args['meta_type'] = 'DATETIME';

  $args['meta_query'] = array(
    'key' => 'start_date',
    'value' => date('Ymd', current_time('timestamp')),
    'compare' => '<'

  return $args;

add_filter('display_posts_shortcode_args', 'be_dps_future_events', 10, 2);

This comment has been minimized.

Copy link
Owner Author

@billerickson billerickson commented Aug 26, 2019

Both $args['post_type'] and $atts['post_type'] should work. I prefer using $args since they are the actual query arguments, so I am limiting this code to shortcodes that are querying that post type. If you're using shortcut arguments you could do an event query without including post_type="event" in the shortcode attributes.

Meta queries should be an array of arrays. See the documentation here. This allows you to do multiple meta queries at once and use the relation parameter to specify if results should match all of the results (AND) or one of them (OR).

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