Search code examples
phpwordpresswoocommercepayment-gatewayorders

How to get Order key for creating custom order return url in WooCommerce


This is the code that I am using to get a custom Order return URL:

global $woocommerce;
$test_order = new WC_Order($order_id);
$test_order_key = $test_order->order_key;
$returnURL = site_url().'/checkout/order-received/7140/'.$test_order_key;

The example URL that I need is:
http://www.example.com/checkout/order-received/[order_number]/key=[wc-order-key]

How do I get [wc-order-key]?

Thanks.


Solution

  • There is 2 ways to get the order key:

    1) From an instance of WC_Order object class using the method get_order_key(), this way:

    // Get an instance of the WC_Order object
    $order_obj = WC_get_order($order_id);
    
    // Get the order key
    $order_key = $test_order->get_order_key();
    $returnURL = site_url().'/checkout/order-received/'.$order_id.'/'.$order_key;
    

    2) Using the WordPress get_post_meta() function from the $order_id, this way:

    // Get the order key
    $order_key = get_post_meta( $order_id, '_order_key', true);
    $returnURL = site_url().'/checkout/order-received/'.$order_id.'/'.$order_key;
    

    The Order number is the Order ID in general…