Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What hook to use once order is created in Woocommerce 3

I have created the following plugin, which is supposed to send a POST HTTP request to an external server when a Woocommerce order is created. However, this is not happening: no request received on the external server, nothing is showing up in wp-content/debug.log (I do have define( 'WP_DEBUG_LOG', true ); in wp-config.php). What am I doing wrong?

<?php
/**
 * Plugin Name: MyPlugin
 */


function my_hook($order_id) {
    $url = "https://example.com/do_something";
    $data = wp_remote_post($url, array(
        'headers'     => array(
            'Authorization' => "Token my_token",
            'Content-Type'  => 'application/json; charset=utf-8',
        ),
        'body'        => json_encode(array('order_id' => $order_id)),
        'method'      => 'POST',
        'data_format' => 'body',
    ));
}
add_action(
    'woocommerce_new_order',
    'my_hook'
);

?>
like image 648
peanut Avatar asked Oct 29 '25 16:10

peanut


1 Answers

Since WooCommerce 4.3.0 the correct hook to be used is woocommerce_checkout_order_created, to send a POST HTTP request to an external server when an order is created. So your code is going to be:

add_action( 'woocommerce_checkout_order_created', 'my_hooked_function_callback', 10 );

function my_hooked_function_callback( $order ) {

    $url = "https://example.com/do_something";

    $data = wp_remote_post( $url, array(
        'headers'     => array(
            'Authorization' => "Token my_token",
            'Content-Type'  => 'application/json; charset=utf-8',
        ),
        'body'        => json_encode( array( 
           'order_id' => $order->get_id() 
        ) ),
        'method'      => 'POST',
        'data_format' => 'body',
    ) );
}

Code goes in functions.php file of the active child theme (or active theme). It should works.

This hook is located inside create_order() method for WC_Checkout Class.

Note: The code will not work for manual created orders via admin.


Additional notes:

  • To update order meta data once order is created you will use instead the action hook woocommerce_checkout_update_order_meta, with 2 available arguments: $order_id and $data (the posted data).
  • To update order data or meta data before order is created you will use instead the action hook woocommerce_checkout_create_order with 2 available arguments: $order and $data (the posted data).
  • To update order items data or meta data before order is created you will use instead the action hook woocommerce_checkout_create_order_line_item with 2 available arguments: $item, $cart_item_key, $values, $order.

Related: How to debug in WooCommerce 3+

like image 127
LoicTheAztec Avatar answered Oct 31 '25 05:10

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!