1

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');
2
  • have you checked the $order object is valid after you call wc_get_order() ? 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. Commented Jul 3, 2020 at 14:29

2 Answers 2

2

The 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();
}
0

I found the answer here: https://stackoverflow.com/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' ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.