如果购物车中没有送货类,请隐藏送货方式

时间:2016-06-16 01:06:03

标签: woocommerce

我一直在寻找线索,但到目前为止我找到的并不起作用。如果购物车中有没有商品且具有特定的运输类别,我想要隐藏运费方式。我找到了隐藏的方法,如果在购物车中有一个类,并且似乎无法调整它以使其适合我。任何人都可以修改这个,以便如果购物车中没有装运班级“Cannabis”,购物车将隐藏本地送货吗?

// Hides other shipping methods if cannabis is in cart
add_filter('woocommerce_package_rates',     'hide_shipping_method_when_shipping_class_product_is_in_cart', 10, 2);

function hide_shipping_method_when_shipping_class_product_is_in_cart($available_shipping_methods, $package)
{

    // Shipping class IDs that need the method removed

    $shipping_class_ids = array(
        31          
    );
    $shipping_services_to_hide = array(
        'wf_shipping_usps:D_PRIORITY_MAIL',
        'wf_shipping_usps:D_EXPRESS_MAIL',
        'wf_shipping_usps:flat_rate_box_priority'
    );
    $shipping_class_exists = false;
    foreach(WC()->cart->cart_contents as $key => $values) {
        if (in_array($values['data']->get_shipping_class_id() , $shipping_class_ids)) {
            $shipping_class_exists = true;
            break;
        }
    }

    if ($shipping_class_exists) {
        foreach($shipping_services_to_hide as & $value) {
            unset($available_shipping_methods[$value]);
        }
    }

    return $available_shipping_methods;
}

1 个答案:

答案 0 :(得分:0)

以下是更新后的代码,如果购物车中没有具有特定运输类别的商品,则会隐藏运送方式。 有关详细信息,请refer this article

// Hides other shipping methods if items of specific Shipping Class is NOT in cart
add_filter('woocommerce_package_rates',     'xa_hide_shipping_method_when_shipping_class_product_is_in_cart', 10, 2);

function xa_hide_shipping_method_when_shipping_class_product_is_in_cart($available_shipping_methods, $package)
{

    // Shipping class IDs that need the method removed

    $shipping_class_ids = array(
        31          
    );
    $shipping_services_to_hide = array(
        'wf_shipping_usps:D_PRIORITY_MAIL',
        'wf_shipping_usps:D_EXPRESS_MAIL',
        'wf_shipping_usps:flat_rate_box_priority'
    );
    $shipping_class_exists = false;
    foreach(WC()->cart->cart_contents as $key => $values) {
        if (in_array($values['data']->get_shipping_class_id() , $shipping_class_ids)) {
            $shipping_class_exists = true;
            break;
        }
    }

    // Negation of shipping class exists.
    if (!$shipping_class_exists) {
        foreach($shipping_services_to_hide as & $value) {
            unset($available_shipping_methods[$value]);
        }
    }

    return $available_shipping_methods;
}