0
votes

I use the Woocommerce Brands plugin and I would like to add the Brand to each product when it is in the cart, like it displays variations.

So Product Name, and then Size: XXX Colour: XXX Brand: XXX

I have tried a few ways of doing it but I can't seem to get it to work.

1

1 Answers

2
votes

Update 2 - Code enhanced and optimized (April 2019)

Now the way to add brand name(s) just as the product attributes names + values in cart items, is also possible using this custom function hooked in woocommerce_get_item_data filter hook.

The code will be a little different (but the same to get the brand data):

add_filter( 'woocommerce_get_item_data', 'customizing_cart_item_data', 10, 2 );
function customizing_cart_item_data( $cart_item_data, $cart_item ) {
    $product = $cart_item['data']; // The WC_Product Object

    // Get product brands as a coma separated string of brand names
    $brands =  implode(', ', wp_get_post_terms($cart_item['product_id'], 'product_brand', ['fields' => 'names']))

    if( ! emty( $brands ) ) {
        $cart_item_data[] = array(
            'name'      => __( 'Brand', 'woocommerce' ),
            'value'     => $brands,
            'display'   => $brands,
        );
    }
    return $cart_item_data;
}

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


Here is the way to add brand name(s) to the product name in cart items using this custom function hooked in woocommerce_cart_item_name filter hook.

As they can be multiple brands set for 1 product, we will display them in a coma separated string (when there is more than 1).

Here is the code:

add_filter( 'woocommerce_cart_item_name', 'customizing_cart_item_name', 10, 3 );
function customizing_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
    $product   = $cart_item['data']; // The WC_Product Object
    $permalink = $product->get_permalink(); // The product permalink

    // Get product brands as a coma separated string of brand names
    $brands = implode(', ', wp_get_post_terms($cart_item['product_id'], 'product_brand', ['fields' => 'names']));

    if ( is_cart() && ! empty( $brands ) )
        return sprintf( '<a href="%s">%s | %s</a>', esc_url( $product_permalink ), $product->get_name(), $brand );
    elseif ( ! empty( $brands ) )
        return  $product_name . ' | ' . $brand;
    else return $product_name;
}

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

All code is tested on Woocommerce 3+ and works.