将自定义购物车商品值添加到WooCommerce订单商品元数据 [英] Add a custom cart item value to WooCommerce order item meta data

查看:97
本文介绍了将自定义购物车商品值添加到WooCommerce订单商品元数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加订单商品元,并希望在用户提交订单时在我的{prefix} woocommerce_order_itemmeta表中看到它.

I'm trying add order item meta and expect to see it in my {prefix}woocommerce_order_itemmeta table when user submit order.

我用woocommerce_add_cart_item_data过滤器添加了我的值:

I add my value with woocommerce_add_cart_item_data filter:

add_filter( 'woocommerce_add_cart_item_data', 'aa_func_20170206100217', 10, 3 );
function aa_func_20170206100217( $cart_item_data, $product_id, $variation_id ) {
    $data = $_POST;

    if ( isset( $data[ 'selected_date_event' ] ) ) {
        $selected_date_event = [
            'selected_date_event' => $data[ 'selected_date_event' ]
        ];

        return array_merge( $cart_item_data, $selected_date_event );
    }

    return $cart_item_data;
}

这是可行的.当我var_dump我的购物车时,肯定存在我的参数.

And this is works. When I var_dump my cart, there definitely my param exists.

但是当用户提交订单时,我在数据库中找不到该参数.

But when user submit order, I can't find this param in my db.

我想念什么?如何将其存储在订单商品meta中?哪个才是最适合这个东西的钩子?

What did I miss? How it can be stored in order item meta? And which is proper hook for this thing?

推荐答案

您需要在订单商品元数据中保存此数据:

You need to save this data in order item meta data:

// ADD THE INFORMATION AS ORDER ITEM META DATA SO THAT IT CAN BE SEEN AS PART OF THE ORDER
add_action('woocommerce_add_order_item_meta','add_product_custom_field_to_order_item_meta', 9, 3 );
function add_product_custom_field_to_order_item_meta( $item_id, $item_values, $item_key ) {
    // the meta-key is 'Date event' because it's going to be the label too
    if( ! empty( $item_values['selected_date_event'] ) )
        wc_update_order_item_meta( $item_id, 'Date event', sanitize_text_field( $item_values['selected_date_event'] ) );
}

代码会出现在您活动的子主题(或主题)的function.php文件或任何插件文件中.

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

This code is tested and works.

因此,这将显示在已收到订单的订单项目数据,我的帐户订单"视图以及电子邮件通知中.

So this will be displayed in Order item data on Order-received, my account Order view and in email notifications.

这篇关于将自定义购物车商品值添加到WooCommerce订单商品元数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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