将 Woocommerce 品牌名称添加到购物车商品名称

Adding Woocommerce Brands names to cart item product names

我使用 Woocommerce Brands 插件,我想在购物车中的每个产品中添加品牌,就像它显示变体一样。

所以产品名称,然后 尺码:XXX 颜色:XXX 品牌:XXX

我已经尝试了几种方法,但我似乎无法让它工作。

更新 2 - 代码增强和优化(2019 年 4 月)

现在添加品牌名称的方法就像购物车项目中的产品属性名称 + 值一样,也可以使用挂钩在 woocommerce_get_item_data[=40= 中的自定义函数] 过滤挂钩。

代码会有点不同(但是获取品牌数据是一样的):

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;
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。


这里是使用 woocommerce_cart_item_name 过滤器挂钩中的自定义函数将品牌名称添加到购物车商品中的产品名称的方法。

由于1个产品可以设置多个品牌,我们将以逗号分隔的字符串显示它们(当超过1个时).

代码如下:

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;
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

所有代码都在 Woocommerce 3+ 上测试并且有效。