Search code examples
phpwordpresswoocommercecartfee

Add a Woocommerce cart fee does not persist in checkout


I use add_fee method to charge my cart price. It works and it is OK but when I click the checkout button and I go to the checkout page or I refresh the page the new price disappear and old price is there . How can I save my price in cart?

function woo_add_cart_fee($cart_obj) {
    global $woocommerce;

    $count = $_POST['qa'];

    $extra_shipping_cost = 0;
    //Loop through the cart to find out the extra costs
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
        //Get the product info
        $_product = $values['data'];

        //Adding together the extra costs
        $extra_shipping_cost = $extra_shipping_cost + $_product->price;
    }

    $extra_shipping_cost = $extra_shipping_cost * $count;
    //Lets check if we actually have a fee, then add it
        if ($extra_shipping_cost) {
            $woocommerce->cart->add_fee( __('count', 'woocommerce'),   $extra_shipping_cost );
        }
}
add_action( 'woocommerce_before_calculate_totals', 'woo_add_cart_fee');

Solution

  • You need to use the woocommerce_cart_calculate_fees hook instead. I have also revisited your code as you should need to store the $_POST['qa']; value to make the fee persistent:

    add_action( 'woocommerce_cart_calculate_fees', 'cart_custom_fee', 20, 1 );
    function cart_custom_fee( $cart_obj ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
        $count = $_POST['qa'];
    
        $extra_shipping_cost = 0;
    
        // Loop through the cart items to find out the extra costs
        foreach ( $cart_obj->get_cart() as $cart_item ) {
    
            //Adding together the extra costs
            $extra_shipping_cost = $extra_shipping_cost + $cart_item['data']->price;
        }
    
        $extra_shipping_cost = $extra_shipping_cost * $count;
    
        //Lets check if we actually have a fee, then add it
        if ( $extra_shipping_cost != 0 ) {
            $cart_obj->add_fee( __('count', 'woocommerce'),   $extra_shipping_cost );
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme).

    This should work as expected now.