• Hello everybody,

    I’m using pre_get_posts to change the default query for the archive of a custom_post_type. I’ve got it working quite well but would appreciate some help with the finishing touches.

    The custom_post_type is called ‘events’ and I’d like the archive page to show all the events posts in chronological order, excluding any events that are start before the current date. I’ve created a custom_field called ‘start_date’ which I’m using to order the posts. I don’t know how to exclude the events that are in the past and would really appreciate any help with doing this.

    Here’s the hook which I’m using in functions.php of my theme

    /* Filter The Events */
    function events_filter($query) {
      if ( !is_admin() && $query->is_main_query() ) {
      	if( $query->is_archive && $query->query['post_type'] == 'events' ) {
      		$query->set('posts_per_page', -1);
      		$query->set('order', 'asc');
      		$query->set('meta_key', 'start_date');
      		$query->set('orderby', 'meta_value_num');
        }
      }
    }
    
    add_action('pre_get_posts','events_filter');
Viewing 1 replies (of 1 total)
  • Thread Starter Laurence Lord

    (@ll782)

    Update to the previously posted code.

    I’ve noticed an error. I shouldn’t have assumed that all $query objects have a ‘post_type’ component. I’ve updated the code as follows and would still appreciate any help with excluding the past events.

    /* Filter The Events */
    function events_filter($query) {
    	if ( !is_admin() && $query->is_main_query() ) {
    		if( $query->is_archive && isset($query->query['post_type']) ) {
    			if( $query->query['post_type'] == 'events' ) {
    				$query->set('posts_per_page', -1);
    				$query->set('order', 'asc');
    				$query->set('meta_key', 'start_date');
    				$query->set('orderby', 'meta_value_num');
    				/* Code to exclude past events needed here. */
    			}
    		}
    	}
    }
    add_action('pre_get_posts','events_filter');
Viewing 1 replies (of 1 total)
  • The topic ‘Filter to exclude past events from custom post type archive’ is closed to new replies.