WordPress.org

Ready to get started?Download WordPress

Forums

Filter to exclude past events from custom post type archive (2 posts)

  1. ll782
    Member
    Posted 8 months ago #

    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');
  2. ll782
    Member
    Posted 8 months ago #

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

Reply

You must log in to post.

About this Topic