By default, events created with The Events Calendar and Events Calendar Pro appear in the WordPress search results on your website. However, the situation may arise where you’d like to exclude events from the WordPress search results instead. For example, perhaps you’d only like users to see your blog posts there.

Don’t worry; you can add a snippet to your WordPress site to make that happen. Let’s see how to exclude events from WordPress search results below!

The snippet

Add the following snippet to your theme’s functions.php file or use this handy Code Snippets plugin:

add_action( 'pre_get_posts', 'my_search_exclude_filter' );
function my_search_exclude_filter( $query ) {
    if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
        $searchable_post_types = get_post_types( array( 'exclude_from_search' => false ) );
        $post_type_to_remove = 'tribe_events';
        if( is_array( $searchable_post_types ) && in_array( $post_type_to_remove, $searchable_post_types ) ) {
            unset( $searchable_post_types[ $post_type_to_remove ] );
            $query->set( 'post_type', $searchable_post_types );
        }
    }
}

Exclude Past Events From WordPress Search Results

If you have a recurring event or multiple recurring events that have already occurred, they can cause the search results to become muddled. Use the following code snippet to prevent past events from appearing in search results.

<?php
function filter_search_results( $query ) {
    if ( is_admin() ) {
        return;
    }

    if ( ! $query->is_main_query() ) {
        return;
    }

    if ( ! $query->is_search ) {
        return;
    }

    $meta_query = [
        'relation' => 'or',
        [
             'key'     => '_EventEndDate',
             'value'   => date('Y-m-d').' 00:00:00',
             'compare' => '>=',
             'type'    => 'DATETIME'

        ],
        [
             'key'     => '_EventStartDate',
             'compare' => 'NOT EXISTS',
        ],
   ];

   $query->set( 'meta_query', $meta_query );

}

add_filter('pre_get_posts', 'filter_search_results');

You can learn more about using custom code snippets in our Knowledgebase.