我的购物车有三种方式:标准配送(0-10kg)、标准配送(11-20kg)和次日配送(0-20kg),我的问题是,当我将冷冻食品配送类别的产品运送到购物车时,配送方式应该是次日配送,如果购物车上现在有配送类别,则只有标准配送,我的问题是,当一个添加了装运类别的产品和一个没有装运类别的产品时,它将不符合我所做的条件。
add_filter( 'woocommerce_package_rates', 'custom_hide_shipping_methods', 10, 2 );
function custom_hide_shipping_methods( $rates, $package ) {
foreach( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item[ 'data' ]; // The WC_Product object
if( $product->get_shipping_class_id() == 149 ) { // <== ID OF MY SHIPPING_CLASS
unset( $rates['shipping_by_rules:16'] ); // standard delivery
wc_add_notice( sprintf( __( '1', 'woocommerce' ), $weight ), 'error' );
}else if($product->get_shipping_class_id() == NULL){
unset( $rates['shipping_by_rules:15'] ); // next day delivery
wc_add_notice( sprintf( __( '2', 'woocommerce' ), $weight ), 'error' );
}else if($product->get_shipping_class_id() != || $product->get_shipping_class_id() == 149){
unset( $rates['shipping_by_rules:16'] ); // standard delivery
wc_add_notice( sprintf( __( '3', 'woocommerce' ), $weight ), 'error' );
}
break; // we stop the loop
}
return $rates;
}
更新2:你的代码中有很多错误…
您的代码中缺少装运方法,因为您只有2个:
“按规则发货:16”
==但标准交货(11-20公斤)如何
您应该尝试以下方法:
add_filter( 'woocommerce_package_rates', 'custom_hide_shipping_methods', 20, 2 );
function custom_hide_shipping_methods( $rates, $package ) {
$targeted_class_id = 149; // <== ID OF MY SHIPPING_CLASS
$has_class = $has_no_class = false;
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
$shipping_class = $cart_item['data']->get_shipping_class_id();
# $weight = $cart_item['data']->get_weight();
if( $shipping_class == $targeted_class_id )
$has_class = true;
elseif( empty( $shipping_class ) )
$has_no_class = true;
}
// Unseting shipping methods
if( $has_class )
{ // CASE 1 and 3
unset( $rates['shipping_by_rules:16'] ); // standard delivery
# wc_add_notice( sprintf( __( '1 | %s', 'woocommerce' ), $weight ), 'error' );
}
elseif( ! $has_class && $has_no_class )
{ // CASE 2
unset( $rates['shipping_by_rules:15'] ); // next day delivery
# wc_add_notice( sprintf( __( '2 | %s', 'woocommerce' ), $weight ), 'error' );
}
elseif( $has_class && $has_no_class ) // ==> Optional (You may not neeed it)
{ // CASE 3
unset( $rates['shipping_by_rules:16'] ); // standard delivery
# wc_add_notice( sprintf( __( '3 | %s', 'woocommerce' ), $weight ), 'error' );
}
return $rates;
}
代码进入函数。活动子主题(或活动主题)的php文件。
它应该有效。