基于 WooCommerce 中购物车商品数量的附加价格
·
问题:基于 WooCommerce 中购物车商品数量的附加价格
基于 "woocommerce 更改结帐和购物车页面中的价格" 更改结帐页面中总价的答案代码,我添加了一些额外的代码来计算用户在购物车中拥有的产品以及用户是否有 9 种产品在购物车中,然后将一些价格添加到总计中:
add_action( 'woocommerce_before_cart_totals', 'custom_cart_total' , 'get_cart_contents_count');
function custom_cart_total() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if (WC()->cart->get_cart_contents_count() == 9){
WC()->cart->total += 15;
}
elseif(WC()->cart->get_cart_contents_count() == 6){
WC()->cart->total += 14;
}
elseif(WC()->cart->get_cart_contents_count() == 4){
WC()->cart->total += 13;
}
}
**但它不起作用。**这张图片将解释一切:

如果有人可以更正代码并告诉我如何显示图片中的消息,我将不胜感激
解答
您应该更好地使用 FEE API,这样:
// Add a custom packing fee based on item count
add_action( 'woocommerce_cart_calculate_fees', 'custom_packing_fee', 10, 1 );
function custom_packing_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 )
return;
$count = $cart->get_cart_contents_count();
if ( $count >= 9 ){
$fee = 15;
}
elseif( $count >= 6 && $count < 9 ){
$fee = 14;
}
elseif( $count >= 4 && $count < 6 ){
$fee = 13;
}
if ( isset($fee) && $fee > 0 ) {
$label = sprintf( __('Box fee (%d items)'), $count);
$cart->add_fee( $label, $fee, false );
}
}
代码进入您的活动子主题_(或活动主题)_的functions.php文件。测试和工作。
如果您想为包装费启用税收,请将第三个参数从
false更改为true。
更多推荐
所有评论(0)