根据 WooCommerce 中的特定购物车总额添加费用
Add fee based on specific cart total in 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
总是return0
, 因为这个钩子在购物车总数计算之前被触发…
You should better use WC()->cart->cart_contents_total
instead.
此外,购物车对象已包含在此挂钩中,因此您可以将其作为参数添加到挂钩函数中。
另外你不需要使用这个钩子 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 ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// The percentage
$percent = 15; // 15%
// The cart total
$cart_total = $cart->cart_contents_total;
// The conditional Calculation
$fee = $cart_total >= 25 ? $cart_total * $percent / 100 : 0;
if ( $fee != 0 )
$cart->add_fee( __( "Gratuity", "woocommerce" ), $fee, false );
}
代码进入您的活动子主题(或主题)的 functions.php 文件或任何插件文件。
此代码已经过测试并且有效。
我正在尝试根据艺术品总额中的特定金额添加费用。我想显示购物车总数是否等于或大于总“$$$”金额添加费用,否则不添加。
我知道将它添加到总数中是有效的,但我认为它不会检查它是否低于美元金额。
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
总是return0
, 因为这个钩子在购物车总数计算之前被触发…
You should better use
WC()->cart->cart_contents_total
instead.
此外,购物车对象已包含在此挂钩中,因此您可以将其作为参数添加到挂钩函数中。
另外你不需要使用这个钩子 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 ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// The percentage
$percent = 15; // 15%
// The cart total
$cart_total = $cart->cart_contents_total;
// The conditional Calculation
$fee = $cart_total >= 25 ? $cart_total * $percent / 100 : 0;
if ( $fee != 0 )
$cart->add_fee( __( "Gratuity", "woocommerce" ), $fee, false );
}
代码进入您的活动子主题(或主题)的 functions.php 文件或任何插件文件。
此代码已经过测试并且有效。