1

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

1 Answer 1

1

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?

1
  • 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?
    – user28566
    Commented Jun 5, 2015 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.