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


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?

| improve this answer | |
  • Please can someone explain the code above, as I don't understand it? Why is event_start_date the key and current_time('mysql') the value? – mattnewbie Jun 5 '15 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.