Access Order Items and WC_Order_Item_Product in WooCommerce 3
One notable change in WooCommerce 3 is the inability to directly access properties from order items. The following code, which previously worked, now results in an error:
$order_item_id = 15; $order_item = new WC_Order_Item_Product($order_item_id); $return = $order_item->get_id() ? $order_item : false;
Understanding the New Mechanisms
In WooCommerce 3, the WC_Order_Item_Product class does not have a constructor, and its properties can be accessed through dedicated methods. The following are the key methods for retrieving specific data:
Retrieving Specific Data
Retrieving Totals
Retrieving Order Items
To retrieve order items from a WC_Order object and access their data (using the WC_Product Object), use the following code:
$order_id = 156; // The order_id $order = wc_get_order( $order_id ); foreach( $order->get_items() as $item_id => $item ){ // Product ID $product_id = $item->get_product_id(); // Variation ID $variation_id = $item->get_variation_id(); // WC_Product Object $product = $item->get_product(); // Product Name $product_name = $item->get_name(); }
Accessing Data and Custom Metadata
Unprotecting Data and Metadata:
$formatted_meta_data = $item->get_formatted_meta_data( ' ', true ); $meta_value = $item->get_meta( 'custom_meta_key', true );
Array Access:
$product_id = $item['product_id']; // Get the product ID $variation_id = $item['variation_id']; // Get the variation ID
Refer to the linked resources below for further insights:
The above is the detailed content of How to Access Order Item Data in WooCommerce 3?. For more information, please follow other related articles on the PHP Chinese website!