Archived topic
Parent products and subcategory products
9 replies · Started by Helen on November 24, 2020
Hi,
I have been trying to prevent the products in a subcategory, from showing on the parent category page. There is a piece of code all over the web, which does not work when added to functions.php or custom functions plug in.
/* Remove child category products from main category page */
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');
In the customise section for the theme I have it set :
Category display
Choose what to display on product category pages.
SHOW PRODUCTS
The individual products are not selected to show in the parent category, nor do they show in the product count on the categories set up section.
Have you come across this before?
Thanks,
Helen
Hi there,
just to be, is the the Category Archive or the main shop page that you want to remove Child Categories?
The products count on the archive page is correct. There should be 8 items. However, on the page view there are 12.
On the parent page (which is populated by woo widgets in the page builder) the same is true. There are 12 products showing, but the extra 4 products do not have the parent category selected, so they should not be showing.
Hi there,
It looks like you've marked this as resolved - did you get it sorted?
Let us know :)
Hi Tom,
No I didn't mark this as completed. I was waiting on feedback.
Thanks,
Helen
Any chance i could see the site?
Try this:
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');
The piece of code that David provided above is just what I'm looking for, except I want to exclude the posts from child categories in the standard WP category not a custom taxonomy.
I tried modifying the above, but darned if I can get it to work. But then I'm not a developer, even in my own dreams, so probably doing something basic and stupid.
Anyway, any help would be appreciated.
THanks
John
Hi John,
As this topic is already solved for the topic starter and is quite different from what you need, can you open a new topic for your concern?
Thank you.