2

In Woocommerce I am trying to find out how to get the product id for a completed order inside the Customer completed order email template to store it as a PHP variable. This way I will be able to insert it into an external database.

I already tried $product->get_id(); but it does not work.

How can get the Product ID in WooCommerce 3+ from email templates?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

1 Answers1

5

You need to loop through Order items… Normally the WC_Order object is defined through the variable $order mostly defined everywhere in email templates.

So the code to get the product ID will be:

// Loop through order items
foreach( $order->get_items() as $item_id => $item ){

    // Get the product ID
    $product_id = $item->get_product_id(); 

    // Get an instance of the WC_Product object
    $product = $item->get_product(); 

    // Get product title (name)
    $product_name = $product->get_title(); // or $product->get_name();

    // Get product price
    $product_price = $product->get_price(); 
}

See this related thread: Get Order items and WC_Order_Item_Product in Woocommerce 3

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • thanks it worked ! Also if i want to get the product name and price as well what I have to add to the code? – Georgios Delimpasis Mar 17 '18 at 00:50
  • helpful answer . Thanks – raihan Jan 30 '20 at 09:10
  • Could you explain why `$product = $item->get_product();` and then `$product->get_id();`doesn't work? In my case it works for simple products but not for variable products, Im confused here, but `$item->get_product_id();` worked out as expected anyways. – svelandiag Jun 23 '20 at 22:27
  • @svelandiag Sorry but there is No variable products in order items only product variations (from a parent variable product)… – LoicTheAztec Jun 23 '20 at 23:59