Search code examples
phpwordpresswoocommercecarttaxonomy-terms

Count only top level WooCommerce product categories form custom shipping calculations


I am using Increase Shipping cost per categories count found in WooCommerce cart answer code from my previous question.

How to exclude subcategories from the array of product categories Ids, to keep only top categories?

According to the solution for this custom calculation, Sub-categories are also included for calculating shipping costs. I would need them to be excluded since they are used only for sorting items.

I tried with adding a filter to the array but brakes the site.


Solution

  • To only count top level product categories (not subcategories), you will replace in Increase Shipping cost per categories count found in WooCommerce cart answer code, the following code block:

        // Loop through cart items for the current shipping package
        foreach( $package['contents'] as $cart_item ){
            $term_ids = array_merge(
                $term_ids,
                (array) $cart_item['data']->get_category_ids()
            );
        }
    

    With this one:

        // Loop through cart items for the current shipping package
        foreach( $package['contents'] as $cart_item ){
            $terms = wp_get_post_terms( $cart_item['product_id'], 'product_cat' );
    
            // Loop through product categories terms for current cart item
            foreach ($terms as $term ) {
                // Only top level product category terms
                if ( $term->parent == 0 ) {
                    // Set the term id in the array
                    $term_ids[] = $term->term_id; 
                }
            }
        }
    

    Tested and works.