Jay
Jay

Reputation: 55

Add product ids and order number as query strings on WooCommerce Thankyou page

The url currently looks like this,

site.com/checkout/order-received/827/?key=wc_order_AN9woFNlCBbXM&product_id=211

I understand that 827 is the order number, but I need it as a string in order to pass data to a form.

I can get the product id in the URL but i can't seem to add the order number. Is there a better solution? How can I add both query strings? Any help is appreciated.

add_filter( 'woocommerce_get_checkout_order_received_url', 'custom_add_product_id_in_order_url', 10, 2 );
function custom_add_product_id_in_order_url( $return_url, $order ) {

    // Create empty array to store url parameters in 
    $sku_list = array();

    // Retrieve products in order
    foreach($order->get_items() as $key => $item){
        $product = wc_get_product($item['product_id']);
        //get sku of each product and insert it in array 

        $sku_list['product_id'] = $product->get_id();
    }

    // Build query strings out of the SKU array
    $url_extension = http_build_query($sku_list);

    // Append our strings to original url
    $modified_url = $return_url.'&'.$url_extension;

    return $modified_url;
}

Upvotes: 2

Views: 1260

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

Your code is a bit outdated since WooCommerce3. To add product ids and order number as query strings for WooCommerce order received page use the following instead:

add_filter( 'woocommerce_get_checkout_order_received_url', 'add_product_ids_in_order_received_url', 10, 2 );
function add_product_ids_in_order_received_url( $return_url, $order ) {
    $product_ids = array(); // Initializing

    // Retrieve products in order
    foreach( $order->get_items() as $item ){
        $product_ids[] = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
    }
    return $return_url . '&number=' . $order->get_order_number() . '&ids=' . implode( ',', $product_ids );
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Now to get the product Ids and order number from URL, you will use something like:

// Get product Ids in an array
if( isset($_GET['ids']) && ! empty($_GET['ids']) ){
    $product_ids_array = explode( ',', esc_attr($_GET['ids']) );
}

// Get order number
if( isset($_GET['number']) && ! empty($_GET['number']) ){
    $order_number = esc_attr($_GET['number']);
}

Upvotes: 3

Related Questions