Wordpress - Get Product id from order id in Woocommerce

WooCommerce 3.0+

you can get the order items of an order by

$order = wc_get_order( $order_id );
$items = $order->get_items();

then if you loop through the items, you can get all the relevant data:

foreach ( $items as $item ) {
    $product_name = $item->get_name();
    $product_id = $item->get_product_id();
    $product_variation_id = $item->get_variation_id();
}

a good tip is to check how the admin order pages get the data, you'll find many answers there!

Pre-WooCommerce 3.0

$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
    $product_name = $item['name'];
    $product_id = $item['product_id'];
    $product_variation_id = $item['variation_id'];
}

I worked on it and achieved something. That I would like to share to other developers. This is not preferred way to do it, but for knowledge I am posting my answer.

global $wpdb;
            $result = $wpdb->get_results('select t1.order_item_id, t2.* FROM 
            wp_woocommerce_order_items as t1 JOIN wp_woocommerce_order_itemmeta as t2 ON t1.order_item_id = t2.order_item_id
            where t1.order_id='.$order->ID);
            echo '<pre>';
            print_r($result);
            echo '</pre>'; 

hope will help someone.

Additionally:

Better to use wordpress table prefix to avoid problems in multiple website or in migration etc.

global $wpdb;
$table_name = $wpdb->prefix . 'table_name'; 

Tags:

Plugins