I'm trying to fix some deprecated functions from this unsupported SagePay plugin.
How can I replace the following snippet of deprecated code in WooCommerce?
foreach ($order->get_items() as $item) {
if ($item['qty']) {
$product = $order->get_product_from_item($item);
I can see that this is its replacement:
@deprecated Add deprecation notices in future release. Replaced with
$item->get_product()
But simply changing it to $product = $item->get_product();
doesn't work. I've also tried changing that line to:
$product = wc_get_product($item['id']);
But it causes an internal server error during the checkout.
You can use WC_data get_data()
method on WC_Order
and WC_Order_Items
objects this way:
// For testing only
$order = wc_get_order(500);
// Iterate though each order item
foreach ($order->get_items() as $item_id => $item) {
// Get the WC_Order_Item_Product object properties in an array
$item_data = $item->get_data();
if ($item['quantity'] > 0) {
// get the WC_Product object
$product = wc_get_product($item['product_id']);
// test output
print_r($product);
}
}
Or with the WC_Order_Item_Product get_product_id()
methods:
// For testing only
$order = wc_get_order(500);
// Iterate though each order item
foreach ($order->get_items() as $item_id => $item) {
if( $item->get_quantity() > 0 ){
// Get the product id from WC_Order_Item_Product object
$product_id = $item->get_product_id();
// get the WC_Product object
$product = wc_get_product($item['product_id']);
// test output
print_r($product);
}
}
All this is working inside the the active theme php files.
When testing in the theme php files I can get the
WC_Product
object with$item->get_product();
Related answer: How to get WooCommerce order details