1
votes

I have applied a specific fee to my WooCommerce cart in the following way:

WC()->cart->add_fee( __( "Delivery Fee"), 50);

What the above code does is that in addition to the Subtotal and Shipping charges, it adds the Delivery Fee to the total and shows the grand total correctly.

I want to now remove the applied fees programmatically, but I am unable to do so.

I tried this, but it does NOT work:

WC()->cart->remove_fees( __( "Delivery Fee"));

Here is my complete code:

add_action( 'woocommerce_before_cart', 'custom_fees' );
function custom_fees() {
    // Add Fees - This WORKS
    WC()->cart->add_fee( __( "Delivery Fee"), 50);

    // Remove Fees - This DOES NOT WORK
    WC()->cart->remove_fees( __( "Delivery Fee"));
}

How can I remove the applied fees programmatically without having to clear the cart?

1

1 Answers

3
votes

Depends on how you need this be, here's one solution:

add_action( 'woocommerce_before_calculate_totals', 'custom_fees' );
function custom_fees() {
    // Add Fees - This WORKS
    WC()->cart->add_fee( __( "Delivery Fee"), 50); // gets removed
    WC()->cart->add_fee( __( "Delivery Fee2"), 150); // will not be removed.

    $fees = WC()->cart->get_fees();
    foreach ($fees as $key => $fee) {
        if($fees[$key]->name === __( "Delivery Fee")) {
            unset($fees[$key]);
        }
    }
    WC()->cart->fees_api()->set_fees($fees);
}