微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 在Woocommerce中为订单添加额外的元数据

我正在为我的网站创建一个自定义插件.

在这插件的某些部分,我需要在每个订单的wp_postMeta中存储额外的元数据.

我在我的插件类中添加了这个:

`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' );
        }

功能不完整,但此代码没有任何反应;我想我需要使用另一个钩子,但我找不到合适的钩子.

有人对这个有了解吗?

我还有$item_id的另一个问题:这是woocommerce全局变量但我在我的插件中看不到它!

我的意思是我无法从我的插件或类似的东西访问此变量!

解决方法:

2018年的方式:

建立在Guido W.P.回答你可以使用woocommerce_checkout_create_order动作钩子
更轻,更有效的版本代码(使用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文件中.

经测试并可在WooCommerce 3中使用(仅限).

一些解释:

woocommerce_checkout_create_order操作挂钩只是保存订单数据之前的一步.请参阅下面WC_Checkout create_order()方法的摘录(包含两个钩子):

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

Why using woocommerce_checkout_create_order instead?:

  • 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.

So this just works with a single line of code inside the function.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐