Giuls
Giuls

Reputation: 580

Change displayed Free shipping label when Free shipping is enabled in Woocommerce

I am using this official woocommerce hook and snippet to Hide other shipping methods when “Free Shipping” is triggered by a coupon. Which works fine.

Currnently, it just displays FREE SHIPPING. I am trying to add in a text line where it displays FREE SHIPPING to say "-£3.95" in order to let the user know that they have saved money off their shipping.

I have tried adding a dummy "fee" inline to the IF statement, but it wont display.

$cart->add_fee( 'You saved -£3.95');

Code is as follows:

    function my_hide_shipping_when_free_is_available( $rates ) {
    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );

e.g. like the following example:

enter image description here

Upvotes: 1

Views: 1315

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254383

There is 2 ways:

1) In your existing code (best way) - It will append your formatted saved price on free shipping:

add_filter( 'woocommerce_package_rates', 'hide_other_shipping_when_free_is_available', 100, 1 );
function hide_other_shipping_when_free_is_available( $rates ) {
    // Here set your saved amount
    $labeleld_price = -3.95;

    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;

            // Here we append the labbelled saved price formated display
            $free[ $rate_id ]->label .= ' (' . strip_tags( wc_price( $labeleld_price ) ) . ')';

            break; // stop the loop
        }
    }
    return ! empty( $free ) ? $free : $rates;
}

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

enter image description here


2) Using settings - Renaming the "Free shipping" label method:

enter image description here

Upvotes: 2

Related Questions