WP SITES

3082 Coded Tutorials & 283 Plugins

Only Show Products From Parent Category on Archive

You can use the pre_get_posts or woocommerce_product_query hook to exclude products assigned to child categories from your parent category archives by using PHP code in your child themes functions file.

add_action( 'woocommerce_product_query', 'wpsites_exclude_child_category_products', 10 );
function wpsites_exclude_child_category_products( $query ) {

if ( !is_admin() && $query->is_main_query() && is_product_category() ) {
    
$term = get_queried_object();

if ( $term->parent == 0 ) { 

$child_ids = get_term_children( $term->term_id, 'product_cat' );

            $query->set( 'tax_query', array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'term_id',
                    'terms'    => $child_ids,
                    'operator' => 'NOT IN',
                ),
            ) );
        }
    }
}

Parent Category 1st

Another option is to show products from your parent category first followed by products from child categories.

Leave a Reply

New Plugins