Filter Shipping method based on shipping class in

2019-05-26 15:10发布

I have been searching for code to filter out any shipping methods other than local pick up, on checkout, when a product that has a specific shipping class selected (Only pickup, ex.) is in the cart (among other products).

I only found code that was outdated and does not work on WC3+.

1条回答
神经病院院长
2楼-- · 2019-05-26 15:54

Here is the way to filter out any shipping methods other than local pick up, when a product that has a specific shipping class enabled:

add_filter( 'woocommerce_package_rates', 'custom_shipping_rates', 100, 2 );
function custom_shipping_rates( $rates, $package ) {

    $shipping_class = 64; // HERE set the shipping class ID
    $found = false;

    // Loop through cart items Checking for the defined shipping method
    foreach( $package['contents'] as $cart_item ) {
        if ( $cart_item['data']->get_shipping_class_id() == $shipping_class ){
            $found = true;
            break;
        }
    }

    if ( ! $found ) return $rates; // If not found we exit

    // Loop through shipping methods
    foreach( $rates as $rate_key => $rate ) {
        // all other shipping methods other than "Local Pickup"
        if ( 'local_pickup' !== $rate->method_id && $found ){

            // Your code here
        }
    }

    return $rates;
}

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

Then in StackOverFlow searching for recent answer with woocommerce_package_rates will allow you to finish your code.

查看更多
登录 后发表回答