将Woocommerce品牌名称添加到购物车产品名称 [英] Adding Woocommerce Brands names to cart item product names
问题描述
我使用了Woocommerce Brands插件,我想将其添加到购物车中的每个产品上,就像它显示变化一样。
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.
因此输入产品名称,然后是
尺寸:XXX
颜色:XXX
品牌:XXX
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.
推荐答案
更新2 -增强和优化代码(2019年4月)
现在可以使用添加到 woocommerce_get_item_data
过滤器挂钩。
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;
}
代码包含在您活动的子主题的function.php文件中(
以下是添加品牌名称的方法)添加到使用 woocommerce_cart_item_name
的自定义功能的购物车商品中的产品名称。
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.
由于它们可以是为一种产品设置的多个品牌,因此我们将用逗号分隔的字符串(当数量超过1个时)显示它们
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).
这是代码:
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+上进行了测试,并且可以正常工作。
All code is tested on Woocommerce 3+ and works.
这篇关于将Woocommerce品牌名称添加到购物车产品名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!