4

I am trying to PHP/MYSQL query WooCommerce Product ID/Variation ID from Order ID

  • If the product(s) in the order is/are simple get product ID(s)

  • If the product(s) in the order is/are variable get Variation ID(s)

  • If both (simple and variable) get both (product ID(s) and Variation ID(s))

NOTE: The script I am coding is independent of WordPress.

Magisch
  • 7,312
  • 9
  • 36
  • 52
Kareem Connor
  • 63
  • 1
  • 6

2 Answers2

9

Using various aspects of the WooCommerce API, this can be accomplished using some version of the following.

$order_id = XXX;

$order = wc_get_order( $order_id ); //returns WC_Order if valid order 
$items = $order->get_items();   //returns an array of WC_Order_item or a child class (i.e. WC_Order_Item_Product)

foreach( $items as $item ) {

    //returns the type (i.e. variable or simple)
    $type = $item->get_type();

    //the product id, always, no matter what type of product
    $product_id = $item->get_product_id();

    //a default
    $variation_id = false;

    //check if this is a variation using is_type
    if( $item->is_type('variable') ) {
        $variation_id = $item->get_variation_id();
    }

    //more code
}

Note the documentation,

wc_get_order();

WC_Order();

WC_Order_Item();

WC_Order_Item_Product();

Chris
  • 4,762
  • 3
  • 44
  • 79
  • 4
    Careful, I'm afraid `$item->get_type()` won't return **variable** or **simple** but **line_item** – Pablo S G Pacheco Mar 15 '21 at 01:18
  • 1
    I wish I had seen @PabloSGPacheco's comment sooner. is_type indeed returns 'line_item' and proves unhelpful. It is probably best to just use `$product_id = $item->get_product_id()` and `$product_variation_id = $item->get_variation_id()`. – Eric K Mar 18 '21 at 15:31
  • 1
    @ericK Glad my comment was useful. Exactly, if I'm not wrong, if you check for `$item->get_variation_id()` in a item which is not a variable product, you get zero. Maybe this is a more reliable approach indeed – Pablo S G Pacheco Mar 19 '21 at 13:11
  • 1
    If you want the product id if simple and the variation id if it's a variation, then you can use this: `$pid = $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id();` – TASan Nov 26 '21 at 10:12
  • I flagged this answer for mod intervention, as it is indeed completely incorrect. get_type cannot be used to ascertain type of product as it will always return "line_item". – Hybrid web dev Mar 15 '22 at 04:40
1

As you mentioned in note "The script I am coding is independent of WordPress".
Then there will be a query that you can use

To get list of variation id from product id.
SELECT ID FROM wp_posts WHERE post_parent = "PRODUCT_ID" AND post_type LIKE 'product_variation'

maulik
  • 919
  • 7
  • 22