Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - Additional price based on cart item count in WooCommerce

Based on "woocommerce change price in checkout and cart page" answer code that change the total price in checkout page, I have added some extra code to count the products that user have in cart and if user had like 9 products in cart then add some price to total:

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; 
    }

}

But it doesn't work. This image will explain everything:

image

I will appreciate if anyone could correct the code and tell me how can I display the message like in the picture

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should better use the FEE API instead, this way:

// 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 );
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...