Let’s check both hooks.
The woocommerce_thankyou
hook is added on line 80 of thankyou.php file.
The hook is getting $order->get_id()
as an argument. So, you have access to the order ID in when you hook to woocommerce_thankyou
in your first example.
But the wp_head
action which is loading from wp_head() function doesn’t have any argument. So, in the second snippet, you don’t have any $order_id
variable.
If you want to get order in head
section, you may need to use WooCommerce functions to get the order and then print it as javascript in head
.
Example:
function tracking_in_head() {
// Get needed data here.
$all_orders = wc_get_orders();
// Check https://docs.woocommerce.com/wc-apidocs/source-function-wc_get_order.html to see WC order functions.
?>
<script>
console.log( 'order_id: <?php echo $order_id; ?>' );
</script>
<?php
}
add_action( 'wp_head', 'tracking_in_head' );