skip to Main Content

Exclude Past Events (Tribe Events Calendar) from Theme Elements

Previously the Events Calendar used to automatically exclude past events from custom queries but it seems like this is no longer the case so if you want to automatically exclude past events from displaying when using theme elements such as the Post Cards you will need to add some custom code to your site. The following snippet parses the query arguments for any theme element to pass an array of past events through the 'post__not_in' parameter when running WP_Query.

/**
 * Exclude past events from theme elements.
 *
 * @link https://total.wpexplorer.com/docs/snippets/exclude-past-tribe-events/
 */
add_filter( 'vcex_query_args', function( $query_args, $shortcode_atts ) {
	if ( ! function_exists( 'tribe_get_events' ) || empty( $query_args ) ) {
		return $query_args;
	}

	$showing_events = false;

	if ( isset( $query_args['post_type'] ) ) {
		if ( is_string( $query_args['post_type'] ) && 'tribe_events' === $query_args['post_type'] ) {
			$showing_events = true;
		} elseif ( is_array( $query_args['post_type'] ) && 1 === count( $query_args['post_type'] ) && in_array( 'tribe_events', $query_args['post_type'] ) ) {
			$showing_events = true;
		}
	}

	if ( $showing_events ) {

		$past_events = [];

		$get_past_events = tribe_get_events( [
			'end_date' => 'now',
		], false );

		if ( $get_past_events ) {
			foreach ( $get_past_events as $past_event ) {
				$past_events[] = $past_event->ID;
			}
		}

		if ( ! isset( $query_args['post__not_in'] ) ) {
			$query_args['post__not_in'] = $past_events;
		} elseif ( is_array( $query_args['post__not_in'] ) ) {
			$query_args['post__not_in'] = array_merge( $query_args['post__not_in'], $past_events );
		}

	}

	return $query_args;
}, 2, 100 );
All PHP snippets should be added via child theme's functions.php file or via the Code Snippets Plugin (or alternative plugin)
Back To Top