【发布时间】:2020-08-22 16:56:38
【问题描述】:
仅当购物车包含特定运输类别的 4 件或更少产品时,我才尝试取消设置两种运输方式。
运送方式:flat_rate:20 和 flat_rate:21
运输等级:182
这就是我所拥有的:
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Shipping Class To Find
$class = 182;
// Number Of Shipping Class Items In Cart
$amount = 4;
// Shipping Methods To Hide
$method_key_ids = array('flat_rate:20', 'flat_rate:21');
// Checking In Cart Items
foreach( $package['contents'] as $item ) {
// If We Find The Shipping Class and Number of Items
if( $item['data']->get_shipping_class_id() == $class && count($package['contents']) <= $amount ){
foreach( $method_key_ids as $method_key_id ){
unset($rates[$method_key_id]); // Remove Targeted Methods
}
break; // Stop The Loop
}
}
return $rates;
}
我想把上面的逻辑和下面的逻辑结合起来:
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_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_ids = array( // Shipping Method rates Ids To Hide
'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'
);
$related_total_qty = 0;
// 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
foreach( $shipping_rates_ids as $shipping_rate_id ) {
if( isset($rates[$shipping_rate_id]) ) {
unset($rates[$shipping_rate_id]); // Remove Targeted Methods
}
}
}
return $rates;
}
创建以下逻辑:
1.如果购物车中有 4 件或更少的运输类别 181 的产品,请取消设置以下运输方式:
- 'flat_rate:20'
- 'flat_rate:21'
2。如果购物车中有 5 种或更多的运输类别 181 的产品,请取消设置以下运输方式:
- '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'
如果我单独使用它们,这两个代码都可以工作。但是当我尝试同时使用两者时出现错误。
我收到以下错误: 无法重新声明 hide_shipping_method_based_on_shipping_class()(之前在 /functions.php:272 中声明)
【问题讨论】:
标签: php wordpress woocommerce shipping-method product-quantity