admin管理员组文章数量:1302930
I am trying to write a function that will allow me to add product meta tags as additional order notes. Unfortunately, nothing works. After a few hours I decided to bring the function to the simplest form to see what does not work.
Each time I place an order for two products. I check my order and see two products. My function should create a note with the text "test 2" but creates a "test 0". And I have no idea why.
function add_engraving_notes($order_id)
{
$order = wc_get_order($order_id);
$note = 'Test';
$items = $order->get_items();
$note .= count($items);
$order->add_order_note($note);
$order->save();
}
add_action('woocommerce_new_order', 'add_engraving_notes');
I am trying to write a function that will allow me to add product meta tags as additional order notes. Unfortunately, nothing works. After a few hours I decided to bring the function to the simplest form to see what does not work.
Each time I place an order for two products. I check my order and see two products. My function should create a note with the text "test 2" but creates a "test 0". And I have no idea why.
function add_engraving_notes($order_id)
{
$order = wc_get_order($order_id);
$note = 'Test';
$items = $order->get_items();
$note .= count($items);
$order->add_order_note($note);
$order->save();
}
add_action('woocommerce_new_order', 'add_engraving_notes');
Share
Improve this question
asked Jul 3, 2020 at 13:52
Todd CoffeeTodd Coffee
111 silver badge2 bronze badges
2
- have you checked the $order object is valid after you call wc_get_order() ? – mozboz Commented Jul 3, 2020 at 14:19
- Yes, I can return things like $order->get_id(); or $order->get_status(); and pass them to the note. – Todd Coffee Commented Jul 3, 2020 at 14:29
2 Answers
Reset to default 2The solution that was provided here did not work for me. It seems that the order items are assigned to the order after the woocommerce_new_order
hook is triggered. I only managed to sort my issues after I changed the hook to woocommerce_checkout_order_processed
as per below:
add_action( 'woocommerce_checkout_order_processed', 'get_order_items_on_checkout', 50, 3 );
function get_order_items_on_checkout($order_id, $posted_data, $order){
$items = $order->get_items();
}
I found the answer here: https://stackoverflow/questions/51014200/wc-order-items-empty
It seems like the get_items call is poorly named or documented as it needs extra parameters. As per the code in the linked answer, you need:
$items = $order->get_items( apply_filters( 'woocommerce_purchase_order_item_types', 'line_item' ) );
本文标签: phpWoocommercegetitems() returns empty array
版权声明:本文标题:php - Woocommerce - get_items() returns empty array 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741731369a2394858.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论