【发布时间】:2021-02-10 18:50:46
【问题描述】:
请你帮我优化我写的小sn-p,在将产品添加到购物车中后应用折扣tech分配了运输类别和其他没有为WordPress(Woocommerce)网站指定类别的产品。
如何优化if .. elseif 并使其整体变得更好。另外,添加break 是一个好习惯吗?我是 PHP 新手,但我目前正在学习并希望改进我的代码。或许我可以使用类似于switch 的东西?非常感谢任何帮助和示例!
add_filter( 'woocommerce_package_rates', 'adjustment_in_rates_of_product_with_shipping_class', 12, 2 );
function adjustment_in_rates_of_product_with_shipping_class( $available_shipping_methods, $package ) {
// Shipping class slug to be eligible for a discount when combined with no class products
$shipping_class = array(
'tech',
);
// Discount
$discounteuro = 3.50;
$discountgbp = 3.20;
$discountusd = 4;
$discountglobalusd = 5;
// Enter the shipping method value
$shipping_services = array(
'flat_rate:5',
);
$shipping_class_exists = false;
foreach(WC()->cart->get_cart_contents() as $key => $values) {
if ( in_array($values['data']->get_shipping_class() , $shipping_class) ) {
$shipping_class_exists = true;
break;
}
}
$shipping_class_no_exists = false;
foreach(WC()->cart->get_cart_contents() as $key => $values) {
if ( strlen($values['data']->get_shipping_class()) == 0 ) {
$shipping_class_no_exists = true;
break;
}
}
if ($shipping_class_exists && $shipping_class_no_exists) {
foreach ($available_shipping_methods as $key => $value) {
if ( in_array($value->get_id() , $shipping_services) && get_woocommerce_currency() == 'EUR' ) {
$available_shipping_methods[$key]->cost -= $discounteuro;
break;
}
elseif ( in_array($value->get_id() , $shipping_services) && get_woocommerce_currency() == 'GBP' ) {
$available_shipping_methods[$key]->cost -= $discountgbp;
break;
}
elseif ( in_array($value->get_id() , $shipping_services) && get_woocommerce_currency() == 'USD' ) {
$available_shipping_methods[$key]->cost -= $discountusd;
break;
}
else {
$available_shipping_methods[$key]->cost -= $discountglobalusd;
break;
}
}
}
return $available_shipping_methods;
}
【问题讨论】:
-
@GrumpyCrouton - 我明白了,所以我将把
break留给$shipping_class_exists和$shipping_class_no_exists,对吧? -
@GrumpyCrouton - 非常感谢。除了您在下面发布的在一个
if中实现所有elseifs 的出色方法之外,您是否也看到了一种同时改进$shipping_class_exists和$shipping_class_no_exists的方法?总的来说,其余的代码好吗?再次感谢您抽出宝贵时间帮助我。非常感谢!
标签: php wordpress if-statement woocommerce shipping-method