InCogKneeToe
InCogKneeToe

Reputation: 23

Rename WooCommerce shipping full label only for specific categories

I am trying to rename a shipping rule label for a specific product category only.

if category = Rain Coats or T-Shirts then shipping role label = custom label

Else display standard label.


I have managed to get the rename working but when I go to specify a category in the code it is just removing all labels or throwing up an error.

Here's the code I have so far, I'm far from an expert so I appreciate this is probably not the correct way to do this.

add_filter( 'woocommerce_cart_shipping_method_full_label', 'change_shipping_label', 10, 2 );

function change_shipping_label() {
    HERE define your product categories in the array (Ids, slugs or names)
    $categories = array( 'rain-coats', 't-shirts' );

    $product_id = $cart_item['product_id'];
    $found = false;

     Loop through cart items to find out specific product categories
    foreach( WC()->cart->get_cart() as $cart_item )
        if( has_term( $categories, 'product_cat', $product_id ) ) {
           $found = true;
            $full_label = str_replace( "Current Label", "New Label", $full_label );
            return $full_label;
        }
}

Any help is greatly appreciated, I'm somewhat a novice at these things.

Upvotes: 1

Views: 122

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253949

There are some mistakes and missing things in your code. Try the following:

add_filter( 'woocommerce_cart_shipping_method_full_label', 'change_shipping_full_label_based_on_product_categories', 10, 2 );
function change_shipping_full_label_based_on_product_categories( $label, $method ) {
    // HERE define your product categories in the array (Ids, slugs or names)
    $categories = array( 'rain-coats', 't-shirts' );

    // Loop through cart items to find out specific product categories
    foreach( WC()->cart->get_cart() as $cart_item ) {
        if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $label = str_replace( "Current Label", "New Label", $label );
            break;
        }
    }
    return $label;
}

Code goes in functions.php file of the active child theme (or active theme). It should works.

Upvotes: 2

Related Questions