1

Background

We have changed the checkout process slightly in WooCommerce

Usually, a user goes: Order Checkout --> Thank you Page (where Order ID appears) --> Upsell page

Now it goes like this: Order Checkout --> Upsell Page

This redirect is achieved using this script:

add_action( 'template_redirect', 'woo_custom_redirect_after_purchase' );
function woo_custom_redirect_after_purchase() {
global $wp;
if ( is_checkout() && !empty( $wp->query_vars['order-received'] ) ) {
wp_redirect( 'https://website.com/upsell/' );
exit;
}
}

Question

The issue here is that I can't extract Order ID from the DOM in the Thank You page because after checkout we immediately redirect users to the Upsell page.

So is there a way to push the Order ID into a Javascript variable on the Upsell Page?

Thank you.

xojijog684
  • 190
  • 2
  • 8

1 Answers1

2

I would not use javascript but would use wc_get_customer_last_order( $customer_id ); on your upsell page to get the lastest order id

// Get user id
$customer_id = get_current_user_id();

// Get last order
$last_order = wc_get_customer_last_order( $customer_id );

// Get order id
$order_id = $last_order->get_id();

echo $order_id;

// EDIT: if you like to use the order id as javascript variable, you can do this in the following way
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
    var order_id = <?php echo $last_order->get_id(); ?>;
    console.log(order_id);
});
</script>
<?php

if you don't have access to the $customer_id (depending on whether guests can order without an account on your webshop?)

You could use a sql query instead to get the latest order ID

7uc1f3r
  • 28,449
  • 17
  • 32
  • 50