I am trying to get the order Item Object from the Item ID when High Performance Order Storage is enabled. Neither the order object nor the item object is known. The order ID is not known either. Only the order item ID is known.
I found this function:
$item = wc_get_order_id_by_order_item_id($item_id);
But it is probably not HPOS compatible, because it's not working.
Can someone kindly provide the way to get the order item object from the item ID?
I'm hoping it's one line and not running through loops because this is custom code that analyzes many order items.
The function wc_get_order_id_by_order_item_id()
allows getting the order ID by an order item ID, but not the order item object.
Note that this function is compatible with High Performance Order Storage (HPOS).
So you need to add some few things to get the order item Object from an item ID. Below you will find a custom lightweight function that does the job:
/**
* Get the Order Item object from the Order Item ID.
*
* @param int $item_id Item ID.
*
* @return object/null Order Item (or null)
*/
function wc_get_order_item_object_by_item_id( $item_id ) {
$order_id = wc_get_order_id_by_order_item_id($item_id);
$order = wc_get_order($order_id); // Get the Order Object
if ( ! is_a($order, 'WC_Order') ) {
return null;
}
// Get all order items
$order_items = $order->get_items( array( 'line_item', 'coupon', 'shipping', 'fee', 'tax' ) );
return isset($order_items[$item_id]) ? $order_items[$item_id] : null;
}
Code goes in functions.php file of your child theme (or in a plugin).
Usage example (from a dynamic item ID):
$item = wc_get_order_item_object_by_item_id( $item_id );
if ( $item && $item->is_type('line-item') ) {
$product_id = $item->get_product_id(); // get the product ID
}
If you want to only get/use order "line items" (products), replace:
// Get all order items
$order_items = $order->get_items( array( 'line_item', 'coupon', 'shipping', 'fee', 'tax' ) );
with:
// Get order items
$order_items = $order->get_items();