Adding Woocommerce Brands names to cart item product names

人盡茶涼 提交于 2019-12-02 09:27:16

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!