Search code examples
phpwordpresswoocommercehook-woocommerce

Get product IDs while using the "woocommerce_payment_complete" hook


My hooks are in theme folder/functions.php

I want tie hook with product_id from order.

tryin this method but they return nothing.

$product->get_id()
or
$product = wc_get_product( $product_id );

Full code

add_action( 'woocommerce_payment_complete', 'so_payment_complete' );
function so_payment_complete($order_id)
{
    $order = wc_get_order($order_id);
    $billingEmail = $order->billing_email;
    $billingName = $order->billing_first_name;
    $product_id = $order->product_id;

    if ($product_id == 980) {
       ......
    }

Solution

  • If you use Woocommerce 3.0+ version, then it should be this.

    I found the answer with this link: https://wordpress.stackexchange.com/questions/97176/get-product-id-from-order-id-in-woocommerce

    In an order can be multiple products, so you have to loop through them. In your code it would look like this:

    add_action( 'woocommerce_payment_complete', 'so_payment_complete' );
    function so_payment_complete($order_id)
    {
        $order = wc_get_order($order_id);
        $billingEmail = $order->billing_email;
        $billingName = $order->billing_first_name;
    
        $items = $order->get_items();
    
        foreach ( $items as $item ) {
            $product_name = $item->get_name();
            $product_id = $item->get_product_id();
            $product_variation_id = $item->get_variation_id();
            if ($product_id == 980) {
                // ....
            }
        }
    }