woocommerce product category search filter showing

2019-07-20 21:42发布

问题:

Any idea why this query is showing products inside a different parent category and it's children? http://botanicaevents.com/rentals/?s=white&product_cat=floral

It should only show the product "White Floral Product Test"

White this query works properly: http://botanicaevents.com/rentals/?s=white&product_cat=rentals Notice how the working string above doesn't show "White Floral Product Test"

Here is the search form:

<form role="search" method="get" id="searchform" action="http://botanicaevents.com/rentals/">
    <div>
        <label class="screen-reader-text" for="s">Search for:</label>
        <input type="text" value="" name="s" id="s" placeholder="Search for products" />
        <input type="hidden" name="product_cat" value="floral" />
        <input type="submit" id="searchsubmit" value="Search" />
    </div>
</form>

The only variation in the form is name="product_cat" value="rentals"

回答1:

The default behavior is that WordPress will search for the search term in the provided WooCommerce category and its child categories. To change that, you may have to use the pre_get_posts action to change the query itself not to include the child categories.

For example:

add_action('pre_get_posts', 'woo_alter_category_search');
function woo_alter_category_search($query) {
    if (is_admin() || !is_search())
        return false;

    if ($product_cat = $query->get('product_cat')) {
        $query->set('product_cat', '');
        $query->set('tax_query', array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => $product_cat,
                'include_children' => false,
            )
        ));
    }
}

Keep in mind that this code is not tested - it is just an example.