Quantcast
Channel: Question and Answer » meta-query
Viewing all articles
Browse latest Browse all 36

How can I apply a meta query for a single custom post type in the main query?

$
0
0

I have custom post type called event, which has custom fields for start_date and end_date. For the event archive, I’m filtering out “expired” events using the following meta query added to the main query inside a pre_get_posts filter, which works fine:

if ( is_post_type_archive( 'event' ) ) {
    $query->set( 'meta_query', array(
        'relation' => 'OR',
        array(
            'key' => 'start_date',
            'value' => $today = date( 'Ymd' ),
            'compare' => '>='
        ),
        array(
            'key' => 'end_date',
            'value' => $today = date( 'Ymd' ),
            'compare' => '>='
        ),
    ) );
}

I’d like to do the same for search queries. Is it possible to add a meta query to the main query and have it only apply to a certain post type (i.e. event)? Pseudocode (I know this doesn’t work, but to illustrate):

if ( is_search() ) {
    $query->set( 'meta_query', array(
        'relation' => 'OR',
        array(
            'key' => 'post_type',
            'value' => 'event',
            'compare' => '!=',
        ),
        array(
            ....
}

Viewing all articles
Browse latest Browse all 36

Trending Articles