admin管理员组

文章数量:1379588

I'm trying to exclude WooCommerce products from default WP search, but I need to keep all other posts types, including CPT and those CPT created in the future. Im trying with:

function searchFilter($query) {
    if (!$query->is_admin && $query->is_search) {
        $query->set('post_type', array('post', 'page', 'CPT'));
    }
    return $query;
}
add_filter('pre_get_posts', 'searchFilter');

In code above I can set in post_type what posts types I want to choose. But I would like to exclude only a 'products' post_type. Is there any way to create parameter like that?

I'm trying to exclude WooCommerce products from default WP search, but I need to keep all other posts types, including CPT and those CPT created in the future. Im trying with:

function searchFilter($query) {
    if (!$query->is_admin && $query->is_search) {
        $query->set('post_type', array('post', 'page', 'CPT'));
    }
    return $query;
}
add_filter('pre_get_posts', 'searchFilter');

In code above I can set in post_type what posts types I want to choose. But I would like to exclude only a 'products' post_type. Is there any way to create parameter like that?

Share Improve this question asked May 4, 2020 at 13:02 D_PD_P 1531 gold badge3 silver badges12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

If you want to exclude the "product" post type (= WooCommerce products) from all front-end searches on your site, you can use this code:

function my_adjust_post_type_args( $args, $post_type ) {
    if ( 'product' === $post_type ) {
        $args['exclude_from_search'] = true;
    }

    return $args;
}

add_filter( 'register_post_type_args', 'my_adjust_post_type_args', 10, 2 );

It modifies the "exclude_from_search" argument when the "product" post type is registered. See the docs for the register_post_type() function for more information.

本文标签: How to exclude specific posttype from default search