Search code examples
phpwordpresswoocommerceproducthook-woocommerce

Getting the value of the product's id value (_product_id) after the payment in WooCommerce


I want to get the value of _product_id on the payout page (thankyou.php), can somebody help me with this.

I have attached an image of the field I need exactly that value

value into database


Solution

  • You can use woocommerce_thankyou hook to get the product ID's in thankyou page

    function wh_getProductIds($order_id)
    {
        //getting order object
        $order = wc_get_order($order_id);
        $product_id_arr = [];
        //getting all line items
        foreach ($order->get_items() as $item)
        {
            $product = $item->get_product();
            $product_id_arr = $product->get_id(); //storing the product ID
            //$product_sku = $product->get_sku();
        }
        //$product_id_arr has all the order's product IDs
        //now you can do your stuff here.
    }
    
    add_action('woocommerce_thankyou', 'wh_getProductIds', 10, 1);
    

    Code goes in functions.php file of your active child theme (or theme). Or also in any plugin php files.
    Code is tested and works. version 3.x or above

    Related:

    Hope this helps!