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
941 views
in Technique[技术] by (71.8m points)

wordpress - woocommerce add fee to cart based on quantity

I wan to add fee based on quantity. For eg: If quantity in cart = 5 , then the fee to be added should be 4$, If quantity in cart = 7, then the fee to be added should be 8$

I have tried this code to get quantity.

add_action('woocommerce_before_calculate_totals', 'woocommerce_custom_surcharge');

function woocommerce_custom_surcharge() {
    global $woocommerce;
$amount =  $woocommerce->cart->get_cart_item_quantities();
if($amount==5)
{
    $excost = 7;
    }
    else if($amount==7){
    $excost = 8;
    }
    $woocommerce->cart->add_fee('Charges delivery', $excost, $taxable = false, $tax_class = '');
}

Please help with the same.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Please Try this

function woocommerce_custom_surcharge(){ 
global $woocommerce;
//Getting Cart Contents. 
$cart = $woocommerce->cart->get_cart();
//Calculating Quantity
foreach($cart as $cart_val => $cid){
        $qty += $cid['quantity']; 
    }
//Your Condition
if($qty==5)
{
    $excost = 7;
    }
    else if($qty==7){
    $excost = 8;
    }

    $woocommerce->cart->add_fee('Charges delivery', $excost, $taxable = false, $tax_class = '');


}

From Here I found that We need to get the quantity of the cart by summing up the values of the cart.Hope this will Solve your problem.


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

...