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
Add a comment  | 

2 Answers 2

Reset to default 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();
}

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