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

时间:2017-09-21 18:00:19

标签: php wordpress woocommerce cart checkout

我使用Woocommerce Brands插件,我想在每个产品放入购物车时添加品牌,就像显示变化一样。

所以产品名称,然后 大小:XXX 颜色:XXX 品牌:XXX

我尝试过几种方法,但我似乎无法让它发挥作用。

1 个答案:

答案 0 :(得分:2)

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

现在,使用此附加在 woocommerce_get_item_data 过滤器钩子中的自定义函数,也可以像在产品属性名称+购物车商品中添加品牌名称一样。< / p>

代码会有所不同(但获取品牌数据的方法相同):

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+上进行测试并且有效。

相关问题