2 回答

TA貢獻1772條經驗 獲得超6個贊
您應該為每個代碼片段使用不同的函數名稱,但最好的方法是將所有內容合并到一個唯一的函數中。
以下是使其在獨特功能中工作的方法(對于來自特定運輸方式的物品):
當購物車中有 4 件或更少的商品時隱藏一些運輸方式
當購物車中有 4 件或更少的商品時隱藏一些其他運輸方式
代碼:
add_filter( 'woocommerce_package_rates', 'show_hide_shipping_methods_based_on_shipping_class', 10, 2 );
function show_hide_shipping_methods_based_on_shipping_class( $rates, $package ) {
$targeted_class_ids = array(182); // Shipping Class To Find
$allowed_max_qty = 4; // Max allowed quantity for the shipping class
$shipping_rates_ids1 = array( // Shipping Method rates Ids To Hide if more than 4 items are in cart
'wf_shipping_ups:07',
'wf_shipping_ups:08',
'wf_shipping_ups:11',
'wf_shipping_ups:54',
'wf_shipping_ups:65',
'wf_shipping_ups:70',
'wf_shipping_ups:74',
'free_shipping:2',
'request_shipping_quote',
);
$shipping_rates_ids2 = array( // Shipping Method rates Ids to Hide if 4 or less items are in cart
'flat_rate:20',
'flat_rate:20',
);
$related_total_qty = 0; // Initializing
// Checking cart items for current package
foreach( $package['contents'] as $key => $cart_item ) {
if( in_array( $cart_item['data']->get_shipping_class_id(), $targeted_class_ids ) ){
$related_total_qty += $cart_item['quantity'];
}
}
// When total allowed quantity is more than allowed (for items from defined shipping classes)
if ( $related_total_qty > $allowed_max_qty ) {
// Hide related defined shipping methods (more than 4 items)
foreach( $shipping_rates_ids1 as $shipping_rate_id ) {
if( isset($rates[$shipping_rate_id]) ) {
unset($rates[$shipping_rate_id]); // Remove Targeted Methods
}
}
} else {
// Hide related defined shipping methods (4 or less items)
foreach( $shipping_rates_ids2 as $shipping_rate_id ) {
if( isset($rates[$shipping_rate_id]) ) {
unset($rates[$shipping_rate_id]); // Remove Targeted Methods
}
}
}
return $rates;
}
代碼位于活動子主題(或活動主題)的functions.php 文件中。未經測試它應該有效。
刷新運輸緩存:
此代碼已保存在您的functions.php 文件中。
在運輸區域設置中,禁用/保存任何運輸方式,然后啟用返回/保存。
你已經完成了,你可以測試它。
處理物品數量而不是物品累計數量:
代替:
$related_total_qty += $cart_item['quantity'];
經過
$related_total_qty++;

TA貢獻1831條經驗 獲得超4個贊
我假設您已經通過依次編寫這兩個代碼片段來組合它們。
由于您兩次使用相同的函數名稱,因此出現錯誤:無法重新聲明......
因此,您可以嘗試通過重命名第二個片段的函數名稱來修復它,如下所示 -
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class_logic_2', 10, 2 );
function hide_shipping_method_based_on_shipping_class_logic_2( $rates, $package ) {
// other stuffs
}
- 2 回答
- 0 關注
- 128 瀏覽
添加回答
舉報