Shaun
Shaun

Reputation: 811

Woocommerce & Wordpress - How to access Order ID on woocommerce_checkout_create_order_line_item

I'm trying to add meta data to each product when an order has been created by using the woocommerce_checkout_create_order_line_item.

However, I can't seem to access the ID of the order.

I've used print_r($order) and can see the order details in there but I can't see the ID of the order within the object. Is this because it hasn't been generated yet?

    add_action('woocommerce_checkout_create_order_line_item', array($this, 'ticket_meta_to_line_item'), 20, 4 );

function ticket_meta_to_line_item( $item, $cart_item_key, $values, $order )
{
    $_p = $item->get_product();
    $key = 'Draw #';
    $order_id = $order->id;
    error_log( print_r( $order, true ) );

    if ( false !== ( $value = $_p->get_meta( $key, true ) ) )
    {
        $numbers = $this->add_tickets_to_order_meta($order_id, $order->get_user_id(), $_p->id);
        error_log( print_r( $numbers, true ) );
        $item->add_meta_data( $key , 1 , true );
    }

}

Upvotes: 1

Views: 1319

Answers (2)

Risha Tiwari
Risha Tiwari

Reputation: 111

If you wondering to add meta data, then there is no need to find the Order_ID, from below code you can easily do so.

function _woocommerce_add_order_item_meta_new_ver($item,$cart_key,$values) { 

//HERE product_meta is just a random key I have used here, you have to use your key here
if (isset ( $values ['product_meta'] )) {

    foreach ( $values ['product_meta'] as $key => $val ) {

        $order_val = stripslashes( $val );

        if($val) {

            if($key == 'your_cart_item_key') {
                $item->add_meta_data('Your Key',$order_val);
            }

        }

    }   

 }

}
//This will add "Your Key" in your order_item_meta, just make sure you have used the same key "your_cart_item_key" in your cart_item_meta key too.

Upvotes: 1

raju_odi
raju_odi

Reputation: 1455

You can access order id using below code.

$order_id = $order->get_order_number();

Tested and works well

Upvotes: -1

Related Questions