How to exclude events (custom posts) from search, if the start date has already passed?

wordpress.stackexchange https://wordpress.stackexchange.com/questions/190402

  •  03-10-2020
  •  | 
  •  

Question

I have a query that is used to display search results from search. The query is in search.php. It shows custom posts and pages in the search result, which is what I want. I have a custom post type called 'event', each post has a date stored in _event_start_date. I want to compare _event_start_date (a meta key) with the current date and exclude event posts that are in the past from the search result.

My working query:

if ( have_posts() ) : ?>
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
<?php while ( have_posts() ) : the_post(); ?>
 <a href="<?php echo get_permalink(  ); ?>"><?php echo the_title(); ?></a>
 <?php endwhile; ?>
 <?php else : ?>
 <p> there were no results </p>
 <?php endif; ?>

How can I include _event_start_date in the above code, so that if an event has already started it is not shown in the search result? The date is formatted as 2015-05-01 in _event_start_date

Was it helpful?

Solution

This works, when I put it in functions.php.

function wpq_modify_search( $q ) {
    if ( ! is_admin() && $q->is_main_query() && $q->is_search() ) {
        $meta_query = [
            'relation' => 'or',
            [
                'key'     => '_event_start_date',
               'value' => current_time( 'mysql' ),
                'type' => 'DATETIME',
                 'compare' => '>=',

            ],
            [
                'key'     => '_event_start_date',
                'compare' => 'NOT EXISTS',
            ],
        ];
        $q->set('meta_query', $meta_query );
    }

}

add_action( 'pre_get_posts', 'wpq_modify_search' );

I don't understand this code though, please can someone explain it please?

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top