3

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Liam McArthur
  • 1,033
  • 3
  • 18
  • 42

1 Answers1

5

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

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • 3
    I originally used `$item->get_product();` but because PhpStorm was underlining it as a non-existent method, I didn't use it. It turns out that this does actually work. I've literally changed that last line to `$product = $item->get_product();` and it now works perfectly. – Liam McArthur Jul 11 '17 at 12:30
  • 1
    @LiamMcArthur I was very surprise that it wasn't working… So stupid editors that are not updated with the new WC methods … happy it's working. – LoicTheAztec Jul 11 '17 at 12:33