【问题标题】:Adding Woocommerce Brands names to cart item product names将 Woocommerce 品牌名称添加到购物车项目产品名称
【发布时间】:2018-03-03 04:33:21
【问题描述】:

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

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

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

【问题讨论】:

    标签: php wordpress woocommerce cart checkout


    【解决方案1】:

    更新 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+ 上进行了测试并且可以运行。

    【讨论】:

    • 谢谢@LoicTheAztec,太好了。是否可以让品牌看起来像一个变体而不是标题? prntscr.com/go7wep
    • @JamesDeadman 这不是相同的代码......我必须更新我的答案......我需要几分钟来测试并进行更改。
    • 非常感谢,这正是我想要的。
    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多