Hide shipping methods for specific shipping class in WooCommerce

前端 未结 2 1776
天涯浪人
天涯浪人 2020-11-30 13:08

Essentially I\'m trying to make the flat rate method Id flat_rate:7 disabled when there is cart items that have the shipping class \"Roller\" (

2条回答
  •  生来不讨喜
    2020-11-30 13:49

    By tweaking LoicTheAztec's code (cheers), I was able to unset a shipping method for each package based on the shipping class of its contents, rather than the cart as a whole. Perhaps it will help someone else too:

    // UNSET A SHIPPING METHOD FOR PACKAGE BASED ON THE SHIPPING CLASS(es) OF ITS CONTENTS
    add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
    function hide_shipping_method_based_on_shipping_class( $rates, $package )
    {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
            return;
        }
    
        foreach( $package['contents'] as $package_item ){ // Look at the shipping class of each item in package
    
            $product_id = $package_item['product_id']; // Grab product_id
            $_product   = wc_get_product( $product_id ); // Get product info using that id
    
            if( $_product->get_shipping_class_id() != 371 ){ // If we DON'T find this shipping class ID
                unset($rates['wbs:9:dae98e94_free_ups_ground']); // Then remove this shipping method
                break; // Stop the loop, since we've already removed the shipping method from this package
            }
        }
        return $rates;
    }
    

    This code allows me to unset my 'Free UPS Ground' shipping if the package contains anything but 'Standard' items (shipping_class_id 371 in my case).

    The scenario from the original post (disable method x if shipping class y) would work like this:

    // UNSET A SHIPPING METHOD FOR PACKAGE BASED ON THE SHIPPING CLASS(es) OF ITS CONTENTS
    add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
    function hide_shipping_method_based_on_shipping_class( $rates, $package )
    {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
            return;
        }
    
        foreach( $package['contents'] as $package_item ){ // Look at the shipping class of each item in package
    
            $product_id = $package_item['product_id']; // Grab product_id
            $_product   = wc_get_product( $product_id ); // Get product info using that id
    
            if( $_product->get_shipping_class_id() == 92 ){ // If we DO find this shipping class ID
                unset($rates['flat_rate:7']); // Then remove this shipping method
                break; // Stop the loop, since we've already removed the shipping method from this package
            }
        }
        return $rates;
    }
    

提交回复
热议问题