I would use something like this:
<?php
$order_id = 123;
print '<script>';
print 'var order_id = "' . $order_id . '";';
print '</script>';
Check the html page source, find your snippet and make sure it looks right with no syntax errors. Check the console for Javascript errors.
Ensure the rest of your javascript runs after the snippet has loaded. Note that order_id becomes a global javascript variable.
If this is the result of an event, you can pass the variable in the event caller, so in php:
print '<button onclick="my_function("'.$order_id.'");">Click me</button>';
and in javascript:
function my_function( order_id ) {
@lorro Thanks for the reply. Just to respond to your question about “if this is the result of an event”, I don’t think it is because the Order ID is just generated on page load on the Thank You page automatically?
I am quite new to this so can you please help me out with the following questions?
Question 1: In this code you provided, how do you pull the actual order ID from WooCommerce instead of a hardcoded 123?
<?php
$order_id = 123;
print '<script>';
print 'var order_id = "' . $order_id . '";';
print '</script>';
Question 2: Apologies for not being clearer but the Order ID first appears on the Thank You page. However, I would only want to retrieve the Order ID into a javascript variable on a different page (an Upsell page). Is it possible to do this?
Thank you.
An “event” is when the user does something, usually click a button.
The $order object is in scope on the thank-you page, so if you have a function which runs there, you can write:
global $order;
$order_id = $order->get_id();
$order won’t be in scope on other pages, so you would need to construct a database query to get all the orders for the current user, then loop through them to find the latest. That’s more code than would normally be provided in a forum answer.
https://stackexchange.com/ is a good resource for coders.