[英]Hide and unhide a specific shipping methods based on shipping class in WooCommerce
我有一個具有三種方法標准交付(0-10kg)、標准交付(11-20kg)和次日交付(0-20kg)的購物車,我的問題是當帶有冷凍食品的產品將 class 運送到購物車時方法應該只在第二天交貨,如果現在購物車上有運費 class,它只有標准交貨,我的問題是當添加帶有運費 class 的產品和沒有運費 class 的產品時,它不會將 go 添加到我做的條件。
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 個:
'shipping_by_rules:16'
==> 標准配送(0-10kg)'shipping_by_rules:15'
==> 次日送達但是標准交貨呢(11-20kg)
您應該嘗試以下操作:
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;
}
代碼進入活動子主題(或活動主題)的 function.php 文件。
它應該有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.