Skip to content

Instantly share code, notes, and snippets.

@stompweb
Created June 29, 2012 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save stompweb/3018263 to your computer and use it in GitHub Desktop.
Save stompweb/3018263 to your computer and use it in GitHub Desktop.
Filter events pre_get_posts
// Function to display only upcoming events for Sugar Events Calendar on the main Events archive.
function sc_filter_events( $query ) {
if( is_post_type_archive('sc_event') && (!is_admin()) && ($query->is_main_query()) ) {
$meta = array(
array(
'key' => 'sc_event_date_time',
'value' => time(),
'compare' => '>='
)
);
$query->set('meta_query',$meta );
$query->set('meta_key', 'sc_event_date_time');
$query->set('orderby', 'meta_value_num');
$query->set('order', 'ASC');
}
}
add_action('pre_get_posts', 'sc_filter_events', 9999);
@stephenh1988
Copy link

Just a heads up- this will fire for all queries (WP_Query, and sometimes get_posts) on post type archive - including secondary ones. You may find that lists of posts in widgets/shortcodes break. Either check $query to see if its a query you want to modify (e.g. check post type). Or to alter only main queries, check $query->is_main_query().

is_post_type_archive will return true (for any query) on a post type archive page for sc_event as this checks only the main query ($wp_query global)

@stompweb
Copy link
Author

Stephen,

Yeah cool, I only wanted to effect the main loop. Thanks for your help, have amended the code.

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