在购物车和结帐的 WooCommerce 产品名称中附加自定义字段值

2023-12-04

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

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

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 );

但我还想更改产品名称。

例如,如果产品名称是Apple和自定义字段'sample_value'值为with sugar,我想得到Apples (with sugar).

我怎样才能实现这个目标?


使用挂钩的自定义函数woocommerce_before_calculate_totals动作挂钩:

// 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;
        }
    }
}

该代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。

这段代码已经过测试并且可以工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在购物车和结帐的 WooCommerce 产品名称中附加自定义字段值 的相关文章

随机推荐