Skip to content

Instantly share code, notes, and snippets.

@ibndawood
Last active January 19, 2021 07:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ibndawood/17ade59c2f856a59e42a5ebf91fbb357 to your computer and use it in GitHub Desktop.
Save ibndawood/17ade59c2f856a59e42a5ebf91fbb357 to your computer and use it in GitHub Desktop.
WooCommerce - Exclude products from child categories
<?php
function exclude_product_cat_children($wp_query) {
if ( isset ( $wp_query->query_vars['product_cat'] ) && $wp_query->is_main_query()) {
$wp_query->set('tax_query', array(
array (
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $wp_query->query_vars['product_cat'],
'include_children' => false
)
) );
}
}
add_filter('pre_get_posts', 'exclude_product_cat_children', PHP_INT_MAX );
@edodere
Copy link

edodere commented Dec 12, 2018

This code works fine, but it breaks admin products search in backend. :/

@cprieto64
Copy link

This code works fine, but it breaks admin products search in backend. :/

same problem. any help?

@ibndawood
Copy link
Author

You can additional conditional tags to make sure the filter is applied only on frontend get_posts and not backend posts.

@durbonca
Copy link

durbonca commented Jul 20, 2020

hi! i corrected as @ibndawood say adding a conditional tag. like this:

`<?php
function exclude_product_cat_children($wp_query) {
if ( is_product_category() ) {
if ( isset ( $wp_query->query_vars['product_cat'] ) && $wp_query->is_main_query()) {
$wp_query->set('tax_query', array(
array (
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $wp_query->query_vars['product_cat'],
'include_children' => false
)
) );
}
} }

add_filter('pre_get_posts', 'exclude_product_cat_children', PHP_INT_MAX );`

more info: https://docs.woocommerce.com/document/conditional-tags/

@benbroadhurst
Copy link

@durbonca this code is returning the error below. Any ideas?

`Your PHP code changes were rolled back due to an error on line 0 of file Unknown. Please fix and try saving again.

Exception thrown without a stack frame`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment