基于 WooCommerce 中购物车商品数量的额外价格

Additional price based on cart item count in 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 文件。已测试并有效。

If you want to enable taxes for the packing fee, change the third argument from false to true.