在Woocommerce中为订单添加额外的元数据 [英] Add extra meta for orders in Woocommerce
问题描述
我正在为我的网站创建自定义插件.
I'm creating a custom plugin for my website.
在此插件的某些部分中,我需要为每个订单将额外的meta存储在wp_postmeta
中.
In some part of this plugin I need to store extra meta in wp_postmeta
for each orders.
我在插件的类中添加了它:
I added this in my plugin's class:
`add_action ('woocommerce_before_checkout_process', array( &$this, 'add_item_meta', 10, 2) );`
这是add_item_meta()
函数:
function add_item_meta( $item_id, $values ) {
wc_add_order_item_meta($item_id, '_has_event', 'yes' );
}
此功能尚未完成,但是此代码没有任何反应;我想我需要使用另一个钩子,但是找不到合适的钩子.
This function is not complete, but nothing happens with this codes; I think I need to use another hook but I can't find a proper one.
有人知道吗?
$item_id
还有另一个问题:这是woocommerce全局变量,但在插件中看不到它!
I also have another problem with $item_id
: this is woocommerce global variable but I can't see it in my plugin!
我的意思是我无法从我的插件或类似的东西访问此变量!
I mean I don't have access to this variable from my plugin or something like this!
推荐答案
2018年方式:
基于 Guido W.P.答案,您可以改用 woocommerce_checkout_create_order
动作挂钩
更轻便有效的版本代码(使用 WC 3+ CRUD方法):
Built on Guido W.P. answer you can use instead woocommerce_checkout_create_order
action hook in
a more lighter and effective version code (using WC 3+ CRUD methods):
add_action('woocommerce_checkout_create_order', 'before_checkout_create_order', 20, 2);
function before_checkout_create_order( $order, $data ) {
$order->update_meta_data( '_custom_meta_key', 'value' );
}
代码进入您的活动子主题(或活动主题)的function.php文件中.
Code goes in function.php file of your active child theme (or active theme).
经过测试并可以在WooCommerce 3+ (仅)中使用.
Tested and works in WooCommerce 3+ (only).
某些说明:
woocommerce_checkout_create_order
操作挂钩仅是保存订单数据之前的一步.参见下面的WC_Checkout
create_order()
方法的提取(带有两个钩子):
The woocommerce_checkout_create_order
action hook is just one step before saving the order data. See below in an extract of the WC_Checkout
create_order()
method (with both hooks):
/**
* Action hook to adjust order before save.
* @since 3.0.0
*/
do_action( 'woocommerce_checkout_create_order', $order, $data );
// Save the order.
$order_id = $order->save();
do_action( 'woocommerce_checkout_update_order_meta', $order_id, $data );
return $order_id;
为什么改用
woocommerce_checkout_create_order
?:
Why using
woocommerce_checkout_create_order
instead?:
- 因为您不需要使用
$order = wc_get_order( $order_id );
,因为您已经在挂钩函数中将$order
作为参数. - 您不需要使用
$order->save();
,因为无论如何(请参见源代码) -
woocommerce_checkout_create_order
也已在WooCommerce版本3中发布,并且也为此提供了帮助.
- Because You don't need to use
$order = wc_get_order( $order_id );
as you already got$order
as an argument in the hooked function. - You don't need to use
$order->save();
as this will be done just after anyway (see the source code) - Also
woocommerce_checkout_create_order
has been released in WooCommerce version 3 and it's maid for that too.
因此,此功能仅在函数内部使用单行代码即可.
这篇关于在Woocommerce中为订单添加额外的元数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!