Skip to content

Instantly share code, notes, and snippets.

@billerickson
Created January 3, 2019 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billerickson/4b5445201fb7046c94f0766f3cba2c91 to your computer and use it in GitHub Desktop.
Save billerickson/4b5445201fb7046c94f0766f3cba2c91 to your computer and use it in GitHub Desktop.
<?php
/**
* DPS Event Queries
* @see https://displayposts.com/2019/01/03/display-upcoming-events-from-sugar-event-calendar/
*/
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(
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 );
@rjdusk
Copy link

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);

@billerickson
Copy link
Author

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