Getting order data after successful checkout hook
Asked Answered
M

3

36

In WooCommerce, I would like to send a request to an API once the customer has successfully checked out. Its basically a website where the client is selling online courses (Like udemy).

When the customer checks out, I would like to send an API request and enroll the user for that particular course. I have tried several WooCommerce hooks but none worked for me.

This is the code that I'm using:

add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1);

function enroll_student($order_id)
{
    echo $order_id;
    echo "Hooked";
}

I am writing this code for a plugin and to make it easier, I am currently using Cash on Delivery method.

Can anyone point me out where I am going wrong because when I checkout I cant see the message "hooked" that I am printing nor the $order_id?

It takes me to the success page and doesn't show these two things that I am printing.

Merocrine answered 1/3, 2017 at 11:33 Comment(0)
W
64

Update 2 Only For Woocommerce 3+ (added restriction to execute the code only once)

add_action('woocommerce_thankyou', 'enroll_student', 10, 1);
function enroll_student( $order_id ) {
    if ( ! $order_id )
        return;

    // Allow code execution only once 
    if( ! get_post_meta( $order_id, '_thankyou_action_done', true ) ) {

        // Get an instance of the WC_Order object
        $order = wc_get_order( $order_id );

        // Get the order key
        $order_key = $order->get_order_key();

        // Get the order number
        $order_key = $order->get_order_number();

        if($order->is_paid())
            $paid = __('yes');
        else
            $paid = __('no');

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

            // Get the product object
            $product = $item->get_product();

            // Get the product Id
            $product_id = $product->get_id();

            // Get the product name
            $product_id = $item->get_name();
        }

        // Output some data
        echo '<p>Order ID: '. $order_id . ' — Order Status: ' . $order->get_status() . ' — Order is paid: ' . $paid . '</p>';

        // Flag the action as done (to avoid repetitions on reload for example)
        $order->update_meta_data( '_thankyou_action_done', true );
        $order->save();
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Related thread:

The code is tested and works.


Updated (to get the product Id from Orders items as asked in your comment)

May be you could use woocommerce_thankyou hook instead, that will display on order-received page your echoed code, this way:

add_action('woocommerce_thankyou', 'enroll_student', 10, 1);
function enroll_student( $order_id ) {

    if ( ! $order_id )
        return;

    // Getting an instance of the order object
    $order = wc_get_order( $order_id );

    if($order->is_paid())
        $paid = 'yes';
    else
        $paid = 'no';

    // iterating through each order items (getting product ID and the product object) 
    // (work for simple and variable products)
    foreach ( $order->get_items() as $item_id => $item ) {

        if( $item['variation_id'] > 0 ){
            $product_id = $item['variation_id']; // variable product
        } else {
            $product_id = $item['product_id']; // simple product
        }

        // Get the product object
        $product = wc_get_product( $product_id );

    }

    // Ouptput some data
    echo '<p>Order ID: '. $order_id . ' — Order Status: ' . $order->get_status() . ' — Order is paid: ' . $paid . '</p>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

The code is tested and works.

Then you can use all class WC_Abstract_Order methods on the $order object.

Related:

Widower answered 1/3, 2017 at 13:50 Comment(10)
Thanks for the answer. I checked it with Thankyou page hook and it showed the desired results but can I get the product data inside this hook. I want to get the product ID after checkout and pass it to an external APIMerocrine
One problem: If the user will refresh thank you page, it will send another request to APICopybook
@Copybook Updated the code for Woocommerce 3 and added a restriction to only allow this code to be executed once.Widower
Problem 2: does not work if an admin manually creates an order. Just ran into that use case myselfBazaar
@Bazaar This question / answer is not related to order creation in backend…Widower
@Widower just thought people should know if they find this! Your solution worked perfectly for me besides that particular use case.Bazaar
@Widower everything going good but facing issue $order->update_meta_data( '_thankyou_action_done', true ); it's not update in databaseFormidable
if( ! get_post_meta( $order_id, '_thankyou_action_done', true ) ) { , the code runs multiple time on reloadOophorectomy
Hello @Widower I tried this one but some time if user use credit card as payment method or sometimes due to some reason if user skip the thank you page then this is not working. I also tried woocommerce_checkout_order_processed but in this hook if we remove some items on cart then it is also considering Do you have any other hook that run after order place with specific items ?Mcabee
This answer is an okay workaround if for some reason you are absolutely locked in to using the woocommerce_thankyou hook, but Nabeel Perwaiz's answer is likely better for most people who just want a hook that fires once after the checkout order is placed, with no need for code to de-dup.Incarcerate
U
19

Rather than 'woocommerce_thankyou' hook, 'woocommerce_checkout_order_processed' hook is the relevant hook. 'woocommerce_checkout_order_processed' hook will be called only once and you will not need to add meta for each product and make additional calls to keep check for code to run only once. As, 'woocommerce_thankyou' can be called multiple times that is each time thankyou page loads. Replace add_action('woocommerce_thankyou', 'enroll_student', 10, 1); with

add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1);

and remove meta code and checks. Updated code is

add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1);
function enroll_student( $order_id ) {
// Getting an instance of the order object
$order = wc_get_order( $order_id );

if($order->is_paid())
   $paid = 'yes';
else
  $paid = 'no';

    // iterating through each order items (getting product ID and the product object) 
// (work for simple and variable products)
foreach ( $order->get_items() as $item_id => $item ) {

    if( $item['variation_id'] > 0 ){
        $product_id = $item['variation_id']; // variable product
    } else {
        $product_id = $item['product_id']; // simple product
    }

    // Get the product object
    $product = wc_get_product( $product_id );

}

// Ouptput some data
echo '<p>Order ID: '. $order_id . ' — Order Status: ' . $order->get_status() . ' — Order is paid: ' . $paid . '</p>';

}

Ugly answered 11/5, 2022 at 3:59 Comment(0)
S
5

you can get the order items of an order by

   // Getting an instance of the order object

    $order = new WC_Order( $order_id );
    $items = $order->get_items();

   //Loop through them, you can get all the relevant data:

    foreach ( $items as $item ) {
        $product_name = $item['name'];
        $product_id = $item['product_id'];
        $product_variation_id = $item['variation_id'];
    }
Sportive answered 1/3, 2017 at 14:53 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.