Update 2 - 代码增强和优化(2019 年 4 月)
现在,也可以使用挂钩的此自定义函数来添加品牌名称,就像购物车项目中的产品属性名称+值一样woocommerce_get_item_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
过滤钩。
由于它们可以是为 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+ 上进行了测试并且可以正常工作。