Reputation: 65
Important note: I am not using functions.php for any cart functionality. I am using standalone php files, it has to stay this way.
In Woocommerce, I'm creating a cart dynamically adding a product using:
global $woocommerce;
$cart = $woocommerce->cart;
//set the custom item data
$item_data = array();
$product_id = '121';
$item_data = array(
'plain_data' => 'test data',
'array_data' => array('URL' => 'URL', 'Signals' => 'SIGNALS')
);
//Add it to the cart
$cart->add_to_cart($product_id, 1, null, null, $item_data);
Then I create the order from the cart using:
global $woocommerce;
$cart = $woocommerce->cart;
$order_data = array('payment_method' => 'PayPal');
$checkout = $woocommerce->checkout();
$order_id = $checkout->create_order($order_data);
But the custom item data that I added does not get saved in the order.
What am I doing wrong?
Upvotes: 1
Views: 1039
Reputation: 253784
As you don't want to use any hook, you will be oblige to set the custom cart item data afterwards once the order is created… So try the following:
Try the following:
$product_id = '121';
$item_data = array(
'plain_data' => 'test data',
'array_data' => array('URL' => 'URL', 'Signals' => 'SIGNALS')
);
$item_data_keys = array_keys($item_data); // Get array keys
//Add it to the cart
WC()->cart->add_to_cart($product_id, 1, 0, array(), $item_data);
// Create order
$order_id = WC()->checkout->create_order( array('payment_method' => 'PayPal') );
// Get an instance of the WC_Order Object
$order = wc_get_order($order_id);
// Loop through order items
foreach( $order->get_items() as $item ){
// Loop though custom item data
foreach( $item_data_keys as $item_data_key ){
// set custom item data
$item->update_meta_data( $item_data_key, $item_data[$item_data_key] );
}
// Save item data
$item->save();
}
// Save order
$order->save();
Tested and works.
NOTE:
global woocommerce
is now replaced byWC()
since a while.
Upvotes: 1