Woocommerce, hide shipping method based on shipping class

╄→尐↘猪︶ㄣ 提交于 2019-11-30 14:52:44

I had same issue and modyfing your code helped. One problem is that "woocommerce_available_shipping_methods" filter is deprecated from WooCommerce 2.1. So you have to use the new one: "woocommerce_package_rates". There is WooCommerce tutorial for similar task, too.

So, I changed filter hook, and when the condition is true, I iterate all shipping methods/rates, find the one I want to display to customer, create new array from it and return this array (with only one item).

I think your problem was (beside deprecated hook) mainly in wrong unset($available_methods[...]) line. It could not work like that.

So here is my code:

add_filter( 'woocommerce_package_rates', 'hide_shipping_based_on_class' ,    10, 2 );
function hide_shipping_based_on_class( $available_methods ) {
    if ( check_cart_for_share() ) {
        foreach($available_methods as $key=>$method) {
            if( strpos($key,'YOUR_METHOD_KEY') !== FALSE ) {
                $new_rates = array();
                $new_rates[$key] = $method;
                return $new_rates;
            }
        }
    }
    return $available_methods;
}

Warning! I found out that woocommerce_package_rates hook is not fired everytime, but only when you change items or quantity of items in your cart. Or it looks like that for me. Maybe those available rates are cached somehow for cart content.

Nishad Up

The bellow code snippet allows you hide the shipping methods based on shipping class. Detailed description is available here

add_filter('woocommerce_package_rates', 'wf_hide_shipping_method_based_on_shipping_class', 10, 2);

function wf_hide_shipping_method_based_on_shipping_class($available_shipping_methods, $package)
{
$hide_when_shipping_class_exist = array(
    42 => array(
        'free_shipping'
    )
);

$hide_when_shipping_class_not_exist = array(
    42 => array(
        'wf_shipping_ups:03',
        'wf_shipping_ups:02',
         'wf_shipping_ups:01'
    ),
    43 => array(
        'free_shipping'
    )
);


$shipping_class_in_cart = array();
foreach(WC()->cart->cart_contents as $key => $values) {
   $shipping_class_in_cart[] = $values['data']->get_shipping_class_id();
}

foreach($hide_when_shipping_class_exist as $class_id => $methods) {
    if(in_array($class_id, $shipping_class_in_cart)){
        foreach($methods as & $current_method) {
            unset($available_shipping_methods[$current_method]);
        }
    }
}
foreach($hide_when_shipping_class_not_exist as $class_id => $methods) {
    if(!in_array($class_id, $shipping_class_in_cart)){
        foreach($methods as & $current_method) {
            unset($available_shipping_methods[$current_method]);
        }
    }
}
return $available_shipping_methods;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!