Last active
January 19, 2021 07:33
-
-
Save ibndawood/17ade59c2f856a59e42a5ebf91fbb357 to your computer and use it in GitHub Desktop.
WooCommerce - Exclude products from child categories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
@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
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/