Hide shipping methods based on products categories in Woocommerce

后端 未结 1 1865
死守一世寂寞
死守一世寂寞 2021-01-14 12:10

With Woocommerce, I would like to hide all shipping methods except \"Local pickup\" when a defined products category is in cart…

The code below does that for other

相关标签:
1条回答
  • 2021-01-14 13:01

    I have revisited your code and here is correct way to make it work for variable products too:

    add_filter( 'woocommerce_package_rates', 'product_category_hide_shipping_methods', 90, 2 );
    function product_category_hide_shipping_methods( $rates, $package ){
    
        // HERE set your product categories in the array (IDs, slugs or names)
        $categories = array( 'clothing');
        $found = false;
    
        // Loop through each cart item Checking for the defined product categories
        foreach( $package['contents'] as $cart_item ) {
            if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
                $found = true;
                break;
            }
        }
    
        $rates_arr = array();
        if ( $found ) {
            foreach($rates as $rate_id => $rate) { 
                if ('local_pickup' === $rate->method_id) {
                    $rates_arr[ $rate_id ] = $rate;
                }
            }
        }
        return !empty( $rates_arr ) ? $rates_arr : $rates;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    You should need to refresh the shipping caches:
    1) First this code is already saved on your function.php file.
    2) In Shipping settings, enter in a Shipping Zone and disable a Shipping Method and "save". Then re-enable that Shipping Method and "save". You are done.

    0 讨论(0)
提交回复
热议问题