使用WooCommerce,在提交新订单后,我在function.php中有以下钩子:
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循环?
注意:当我尝试var_dump($items)时;在foreach循环之前给它我
array(0) {
}
为什么即使在新订单生成后有产品,也无法获得产品详细信息?
解决方法:
Update 2 — The working solution (using an email notification 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对象,因为我们将它作为此钩子函数中的参数.
所以这是你的最终功能代码:
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
}
}
}
这是对这个问题的有效和可行的答案
相关工作答案:
> Sending an SMS for specific email notifications and order statuses
> Avoid repetitive emails notification on some auto completed orders
> Change the user role on purchase for specific products when order status is completed
Update 1 (hook alternative)
尝试使用woocommerce_thankyou钩子,在处理完订单后在审核订单上触发:
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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。