Issue when trying get the product variation object from order items

Viewed 301

on WooCommerce, I'm trying to get the variation name of a product. But I'm getting the message error : Call to undefined function wc_get_product(). Here is the code: (the file where this code is, is from a application that make some request to the server, so it isn't on the root directory).

$order_items = $order_data->line_items;
foreach ($order_items as $order_item) {
    if ($order_item->product_id == $product_id) {
        // Get variation if any
        $variation_id = $order_item->variation_id;
        $variation_name = wc_get_product($variation_id);
        $variation_name->get_formatted_name();

        if (empty($variation_id)) $variation_id = 0;

        $variation_prop = $product['variations'][$variation_id];
    }

}

Any help is appreciated.

EDITED 2: The $order_data is got this way:

try {
                $woocommerce = new Client($f3->get('wprestbaseurl'), $f3->get('wprestconsumer_key'), $f3->get('wpconsumer_secret'), ['wp_api' => true, 'version' => 'wc/v3', 'query_string_auth' => (0 === strpos(strtolower($f3->get('wprestbaseurl')), 'https://'))]);
                // Retrieve given order meta data
                // System IDs are stored into the "xlspadlock_activations" custom field for each order.
                $order_data = $woocommerce->get("orders/$customer_order_id");
            }
catch{....
1 Answers

Update 3

After your update and comments, As it seems that you are using some Rest API on an external file, WooCommerce Classes and methods can't work and will throw errors if you try to use them.


Initial answer:

Your code has some mistakes since WooCommerce 3, as order items and product properties can't not be accessed directly.

Use instead WC_Order_Item_Product get product_id(), get_variation_id() and get_product() methods as follows:

$order_items = $order->get_items(); // Get order items

// Loop through order items
foreach ( $order_items as $item) {
    // Check for specific product Id and only for product variation items
    if ( in_array( $product_id, array($item->get product_id(), $item->get variation_id() ) ) && $item->get variation_id() > 0 ) {
        // Get product variation object
        $product_variation = $item->get_product();

        // Get the product variation formatted name
        $formatted_name   = $product_variation->get_formatted_name();
        
        // ...
    }
}

Related threads:

Notes: On order items, when an item is a product variation, the method get product_id() is the parent variable product Id and the method get_product() gives the product variation instance object.

Related