Get_item () function Woocommerce returns false

With WooCommerce 3+ introducing a new API for fetching order and order details, a lot has changed and a lot of things have broken too.

Consider the following code in my plugin:

$order = wc_get_order($order_id);
$id= 27;

var_dump($order->get_item($id));

      

which gives me bool (false) . I have checked the database and the order and the item exists.

Besides

var_dump($order)

returns the entire order object with all items.

Thus, usually only the function works get_item

.

+3


source to share


1 answer


The only explanation is that the identifier you are using is not of type ... item_id

"line_item"

I tried and it works fine as expected using the method when it is of type "Line_Item". WC_Abstract_Order

get_item()

item_id

To get and check the correct item IDs from a specific order ID try: "line_item"



// define an exiting order ID first
$order_id = 422;

$order = wc_get_order($order_id);

foreach($order->get_items() as $item_id => $item_values){
    $item_ids_array[] = $item_id;
}

var_dump( $item_ids_array ); // will output all item IDs (of type "line_item") for this order

## ==> Then now you can try (to check get_item() method):

foreach( $item_ids_array as $item_id ){
    var_dump( $order->get_item( $item_id ) ); //  Will output each WC_Order_Item_Product Object …
}

      

This should clarify the situation.

As a reference: How to get WooCommerce order details

0


source







All Articles