If you don’t want a query to run on the admin you can call the conditional function is_admin()
to check, if it returns true you can just return out of the function. Additionally, pre_get_posts
is an action hook.
function exclude_product_cat_children( $wp_query ) {
if( is_admin() ) {
return;
}
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_action('pre_get_posts', 'exclude_product_cat_children');