【问题标题】:Append custom field value in WooCommerce product name on cart and checkout在购物车和结帐的 WooCommerce 产品名称中附加自定义字段值
【发布时间】:2018-01-07 00:37:12
【问题描述】:

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

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

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

我怎样才能做到这一点?

【问题讨论】:

    标签: php wordpress woocommerce cart custom-fields


    【解决方案1】:

    使用在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 文件中或任何插件文件中。

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

    【讨论】:

    • 这对我不起作用,但是当我删除 empty() 函数时它起作用了。
    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2017-01-08
    • 2018-07-16
    • 2017-10-09
    • 2018-06-03
    相关资源
    最近更新 更多