Exclude custom post type from search by custom field value?

You need to implement a hook for pre_get_posts filter, in which you can set what you need. Pay attention that you should change only search query, so you have to check if is_search() method returns true. The hook should look like this:

add_filter( 'pre_get_posts', 'wpse8170_pre_get_posts' );
function wpse8170_pre_get_posts( WP_Query $query ) {
    if ( $query->is_search() ) {
        $query->set( 'post_type', array( 'resources' ) );
        $query->set( 'meta_query', array(
            array(
                'key' => 'resource_usertype',
                'value' => array('Public', 'Students', 'Alumni'),
                'compare' => 'IN',
            )
        ) );
    }

    return $query;
}

Leave a Comment