gpt4 book ai didi

php - 无法从新订单 Hook 函数的 order_id 获取产品详细信息

转载 作者:可可西里 更新时间:2023-11-01 00:40:25 24 4
gpt4 key购买 nike

使用 WooCommerce,在提交新订单后,我的 function.php 中有以下 Hook :

add_action( 'woocommerce_new_order', 'create_job_openings');
function create_job_openings($order_id) {

$order = new WC_Order($order_id);
$items = $order->get_items();

foreach ($order->get_items() as $key => $item) {
$product_name = $item['name'];
var_dump($product_name);
}
}

上面的代码没有给我任何输出,因为它没有进入 foreach 循环,这就是为什么 var_dump() 没有给我任何输出,但是如果我特别提到 order_id 就像 create_job_openings($order_id=517) 它有效,即使我在 foreach 循环之前尝试了 echo $order_id ,它给了我order_id,那么为什么它没有进入 foreach 循环?

注意:当我在 foreach 循环之前尝试 var_dump($items); 时它给了我

array(0) {
}

为什么新下单后里面有商品却获取不到商品详情?

最佳答案

Update 2 — The working solution (using an email notification hook)

问题是当使用电子邮件通知 Hook 时可以触发一个操作2 次 ,例如在发出新订单时(商店经理的通知和客户的通知)。

您想对处于“处理中”状态的订单使用此“新订单”事件。

To avoid your action to be fired 2 times using New order notification WooCommerce event, we use 'customer_processing_order' instead of 'new_order' email ID (notification event).

这里我们不需要获取 $order 对象,因为我们在这个钩子(Hook)函数中将其作为参数获取。

所以这是你的最终功能代码:

add_action( 'woocommerce_email_before_order_table', 'custom_action_on_completed_customer_email_notification', 10, 4 );
function custom_action_on_completed_customer_email_notification( $order, $sent_to_admin, $plain_text, $email ) {

if( 'customer_processing_order' == $email->id ){ // for processing order status customer notification…
foreach ($order->get_items() as $item_id => $item_values) {
$product_name = $item_values['name'];
echo $product_name;
break; // (optional) stop loop to first item
}
}
}

这是对这个问题的有效答案

相关工作答案:


Update 1 (hook alternative)

尝试使用 woocommerce_thankyou 钩子(Hook),在处理订单后触发审核订单:

add_action( 'woocommerce_thankyou', 'create_job_openings', 10, 1 );
function create_job_openings( $order_id ) {
if ( ! $order_id )
return;

$order = wc_get_order( $order_id );

foreach ($order->get_items() as $item_id => $item_values) {
$product_name = $item_values['name'];
var_dump($product_name);
break; // (optional) stop loop to first item
}
}

(不适用于 OP)


你应该试试这个 wc_get_order() 以这种方式运行,您的代码将是:

add_action( 'woocommerce_new_order', 'create_job_openings', 10, 1);
function create_job_openings($order_id) {

$order = wc_get_order( $order_id );
$order_items = $order->get_items();

foreach ($order_items as $item_id => $item_values) {
$product_name = $item_values['name'];
var_dump($product_name);
break; // (optional) stops on first item
}
}

你可以看看 How to get WooCommerce order details那里解释了很多事情……

(不适用于 OP)

关于php - 无法从新订单 Hook 函数的 order_id 获取产品详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41605256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com