将产品中的自定义元数据添加到 Woocommerce 中的订单项目 [英] Adding Custom Meta Data from Products to Orders items in Woocommerce

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

问题描述

我正在尝试将我的 woocommerce 产品的自定义元数据添加到我的 Woocommerce Admin 中的订单列中,但此代码不适用于 Wordpress 主题中的 function.php.

I'm trying to get the Custom Meta data of my woocommerce products to my Order Columns in my Woocommerce Admin but this code wont work on my function.php in Wordpress Theme.

// Order Get Meta for PD Number
add_action('woocommerce_add_order_item_meta','adding_custom_data_in_order_items_meta', 1, 3 );
function adding_custom_data_in_order_items_meta( $post_id, $cart_item_key ) {

    // The corresponding Product Id for the item:
    $product_id = $post_id[ 'product_id' ];
    //$pd_number = $post_id['_pd_number'];
    //$pd_number = $_POST['_pd_number'];
    $pd_number = get_post_meta( $post_id[ 'product_id' ], '_pd_number', true );

    if ( !empty($pd_number) ) 
        wc_add_order_item_meta($post_id, '_pd_number', $pd_number, true);
}

谢谢

推荐答案

从 Woocommerce 3 开始,推荐使用更好的钩子(参见 这个答案 线程).

您的代码中存在一些错误.试试这个:

There is some errors in your code. Try this instead:

// Add the the product custom field as item meta data in the order
add_action( 'woocommerce_add_order_item_meta', 'pd_number_order_meta_data', 10, 3 );
function pd_number_order_meta_data( $item_id, $cart_item, $cart_item_key ) {
    // get the product custom field value
    $pd_number = get_post_meta( $cart_item[ 'product_id' ], '_pd_number', true );

    // Add the custom field value to order item meta
    if( ! empty($pd_number) )
        wc_update_order_item_meta( $item_id, '_pd_number', $pd_number );
}

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

这应该适用于从 2.5.x 到 3+ 的 WooCommerce 版本.

This should works on WooCommerce versions from 2.5.x to 3+.

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

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