I’m using the woocommerce_thankyou hook in my WooCommerce site to send order data to an external URL via a POST request whenever a new order is created. However, I’ve noticed that this hook is sometimes triggering on very old orders, causing unexpected POST requests. Here’s the code I’m using:
add_action('woocommerce_thankyou', 'send_order_to_external_url', 10, 1);
function send_order_to_external_url($order_id) {
if (!$order_id) {
return;
}
// Get the order details
$order = wc_get_order($order_id);
// Prepare the data to send
$data = array(
'order_id' => $order_id,
'order_total' => $order->get_total(),
'billing_email' => $order->get_billing_email(),
'billing_phone' => $order->get_billing_phone(),
// Add other necessary order details here
);
// Convert data to JSON
$json_data = json_encode($data);
// The endpoint URL
$url = 'https://example.com/your-endpoint';
// Send the data via wp_remote_post
$response = wp_remote_post($url, array(
'method' => 'POST',
'body' => $json_data,
'headers' => array(
'Content-Type' => 'application/json',
),
));
// Check for errors (optional)
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
error_log('Error sending order data: ' . $error_message);
}
}
My questions are:
- Why might the woocommerce_thankyou hook be triggering on old orders?
- How can I prevent this hook from triggering on anything but newly created orders?
Any insights or suggestions to debug and fix this issue would be greatly appreciated!