当购物车有分配了特定发货类别的产品时,禁用免费发货方式

时间:2020-07-02 作者:Ugur Terzi

您能告诉我,当购物车中有分配了特定装运类别的产品时,我如何修改此代码段(它禁用了特定产品的免费装运方法)以使禁用免费装运方法成为可能?(WooCommerce 4.2以上)

感谢您的帮助。谢谢

function my_free_shipping( $is_available ) {
    global $woocommerce;

    // set the product ids that are ineligible
    $ineligible = array( \'4743\' );

    // get cart contents
    $cart_items = $woocommerce->cart->get_cart();
    
    // loop through the items looking for one in the ineligible array
    foreach ( $cart_items as $key => $item ) {
        if( in_array( $item[\'product_id\'], $ineligible ) ) {
            return false;
        }
    }

    // nothing found return the default value
    return $is_available;
}
add_filter( \'woocommerce_shipping_free_shipping_is_available\', \'my_free_shipping\', 20 );  

1 个回复
最合适的回答,由SO网友:Ivan Shatsky 整理而成

尝试以下操作:

function hide_shipping_methods( $available_shipping_methods, $package ) {
    $shipping_classes = array( \'some-shipping-class-1\', \'some-shipping-class-2\' );
    $excluded_methods = array( \'free_shipping\' );
    $shipping_class_exists = false;
    foreach( $package[\'contents\'] as $key => $value )
        if ( in_array( $value[\'data\']->get_shipping_class(), $shipping_classes ) ) {
            $shipping_class_exists = true;
            break;
        }
    if ( $shipping_class_exists ) {
        $methods_to_exclude = array();
        foreach( $available_shipping_methods as $method => $method_obj )
            if ( in_array( $method_obj->method_id, $excluded_methods ) )
                $methods_to_exclude[] = $method;
        if ( $methods_to_exclude )
            foreach ( $methods_to_exclude as $method )
                unset( $available_shipping_methods[$method] );
    }
    return $available_shipping_methods;
}
add_filter( \'woocommerce_package_rates\', \'hide_shipping_methods\', 10, 2 );
在这里$shipping_classes 是装运类slug和$excluded_methods 如果购物车中至少有一个产品属于这些装运类别之一,则为排除的装运方法的数组。

相关推荐