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'
);
?>
3
Answers
If you go inside class-wc-checkout you will find the create_order function which trigger these hooks just before ending:
Maybe you just have to use one of those?
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: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 forWC_Checkout
Class.Note: The code will not work for manual created orders via admin.
Additional notes:
woocommerce_checkout_update_order_meta
, with 2 available arguments:$order_id
and$data
(the posted data).woocommerce_checkout_create_order
with 2 available arguments: $order and$data
(the posted data).woocommerce_checkout_create_order_line_item
with 2 available arguments: $item,$cart_item_key
,$values
,$order
.Related: How to debug in WooCommerce 3
Short answer use
woocommerce_checkout_order_processed
.Source: https://stackoverflow.com/a/72195252/3261332