Filter Shipping method based on shipping class in Woocommerce 3

坚强是说给别人听的谎言 提交于 2019-12-12 10:09:59

问题


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:


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.



来源:https://stackoverflow.com/questions/49847171/filter-shipping-method-based-on-shipping-class-in-woocommerce-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!