在购物车上的WooCommerce产品名称中添加自定义字段值并结帐 [英] Append custom field value in WooCommerce product name on cart and checkout

查看:81
本文介绍了在购物车上的WooCommerce产品名称中添加自定义字段值并结帐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在购物车和结帐页面中更改产品名称。

I'm trying to change the name of the product in cart and checkout pages.

我有以下代码来添加一些购物车元数据:

I have the following code to add some cart meta data:

function render_meta_on_cart_and_checkout( $cart_data, $cart_item = null ) {
    $custom_items = array();
    /* Woo 2.4.2 updates */
    if( !empty( $cart_data ) ) {
        $custom_items = $cart_data;
    }

    if( isset( $cart_item['sample_name'] ) ) {
        $custom_items[] = array( "name" => $cart_item['sample_name'], "value" => $cart_item['sample_value'] );
    }
    return $custom_items;
}
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2 );

但是我也想更改产品名称。

But I also want to change the name of the product.

例如,如果产品名称为 Apple 和自定义字段 'sample_value' 的值是 加糖 ,我想获得 苹果(加糖)

For example if the product name is Apple and custom field 'sample_value' value is with sugar, I would like to get Apples (with sugar).

如何实现?

推荐答案

使用自定义函数钩在 woocommerce_before_calculate_totals 动作钩子中:

Using a custom function hooked in woocommerce_before_calculate_totals action hook:

// Changing the cart item name
add_action( 'woocommerce_before_calculate_totals', 'customizing_cart_items_name', 20, 1 );
function customizing_cart_items_name( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through each cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Continue if we get the custom 'sample_name' for the current cart item
        if( empty( $cart_item['sample_name'] ) ){
            // Get an instance of the WC_Product Object
            $product = $cart_item['data'];
            // Get the product name (Added compatibility with Woocommerce 3+)
            $product_name = method_exists( $product, 'get_name' ) ? $product->get_name() : $product->post->post_title;
            // The new string composite name
            $product_name .= ' (' . $cart_item['sample_name'] . ')';

            // Set the new composite name (WooCommerce versions 2.5.x to 3+)
            if( method_exists( $product, 'set_name' ) ) 
                $product->set_name( $product_name );
            else
                $product->post->post_title = $product_name;
        }
    }
}

代码

此代码已经过测试并且可以正常工作。

This code is tested and works.

这篇关于在购物车上的WooCommerce产品名称中添加自定义字段值并结帐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆