Search code examples
wordpresswoocommerceproductorderscoupon

How to get product id using order items id in woocommerce


I have Created a coupon programmatically using this documentation -> https://docs.woocommerce.com/document/create-a-coupon-programatically/

It's work good and generate one dynamic coupon code after complete the order. But i want to allow that coupon code only for that ordered product.

So on above code here:

update_post_meta( $new_coupon_id, 'product_ids', '' );

i want to get that order product ID using that order item id.

So any one know solutions for this then please help me.

Thanks, Ketan.


Solution

  • You can get product_id by using $order->get_items() function in WooCommerce

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