根据WooCommerce中的特定购物车总额添加费用
问题描述:
我想根据艺术总额中的特定金额添加费用。我想显示购物车总数是否等于或大于总“$$$”金额添加费用,否则不要添加。根据WooCommerce中的特定购物车总额添加费用
我知道这项工作将其添加到总计,但我不认为它是检查,看它是否低于美元金额。
function woo_add_custom_fees(){
$cart_total = 0;
// Set here your percentage
$percentage = 0.15;
foreach(WC()->cart->get_cart() as $item){
$cart_total += $item["line_total"];
}
$fee = $cart_total * $percentage;
if ( WC()->cart->total >= 25) {
WC()->cart->add_fee("Gratuity", $fee, false, '');
}
else {
return WC()->cart->total;
}
}
add_action('woocommerce_cart_calculate_fees' , 'woo_add_custom_fees');
add_action('woocommerce_after_cart_item_quantity_update', 'woo_add_custom_fees');
我在做什么错了?
答
在woocommerce_cart_calculate_fees
行动挂钩,WC()->cart->total
总是返回0
,因为这钩子的车总金额计算之前解雇......
你应该更好地利用
WC()->cart->cart_contents_total
代替。
另外cart对象已经包含在这个钩子中,所以你可以把它作为一个参数添加到你的钩子函数中。
你也不需要使用这个钩子woocommerce_after_cart_item_quantity_update
。
这是你重新编号:
add_action('woocommerce_cart_calculate_fees', 'custom_fee_based_on_cart_total', 10, 1);
function custom_fee_based_on_cart_total($cart_object) {
if (is_admin() && ! defined('DOING_AJAX')) return;
// The percetage
$percent = 15; // 15%
// The cart total
$cart_total = $cart_object->cart_contents_total;
// The conditional Calculation
$fee = $cart_total >= 25 ? $cart_total * $percent/100 : 0;
if ($fee != 0)
$cart_object->add_fee(__("Gratuity", "woocommerce"), $fee, false);
}
代码放在您的活动子主题(或主题)的function.php文件或也以任何插件文件。
此代码已经过测试并可正常工作。
+0
谢谢!这绝对有帮助 – nholloway4
'else'部分是“下” – Reigel