dataeater
dataeater

Reputation: 23

Woocommerce: product id in the order received url

I would like to change the order received (thanks page) url for a new one, which includes the ordered product's ID.

Here is the code in the class-wc-order.php

/**
 * Generates a URL for the thanks page (order received).
 *
 * @return string
 */
public function get_checkout_order_received_url() {
    $order_received_url = wc_get_endpoint_url( 'order-received', $this->get_id(), wc_get_page_permalink( 'checkout' ));

    if ( 'yes' === get_option( 'woocommerce_force_ssl_checkout' ) || is_ssl() ) {
        $order_received_url = str_replace( 'http:', 'https:', $order_received_url );
    }

    $order_received_url = add_query_arg( 'key', $this->get_order_key(), $order_received_url );

    return apply_filters( 'woocommerce_get_checkout_order_received_url', $order_received_url, $product, $this, $product->id );
}

Any idea? Thanks!

Upvotes: 1

Views: 2299

Answers (1)

MhdSyrwan
MhdSyrwan

Reputation: 1633

This answer on wordpress.stackexchange.com would solve the issue

As a brief, just define the following hook:

add_filter('woocommerce_get_checkout_order_received_url','override_return_url',10,2);

function override_return_url($return_url,$order){

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

    // retrive 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_'.$item['product_id'] . 'sku'] = $product->get_sku();
    }
    //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;
}

Then, you can set the analytics goal to point to the destination below as a regular expression

\/checkout\/order-received\/\d+\/\?key=\w+&product_ID_HERE_sku=SKU_HERE


We can make it simpler by including only product ids:

add_filter('woocommerce_get_checkout_order_received_url','override_return_url',0,2);

function override_return_url($return_url,$order){
  $ids = array();
  foreach($order->get_items() as $key => $item)
  {
    $ids[] = $item['product_id'];
  }
  return add_query_arg('product_ids', join(',', $ids) , $return_url);
}

In this case, the regex would be:

\/checkout\/order-received\/\d+\/\?key=\w+&product_ids=ID1,ID2,ID3

Or for a single product id:

\/checkout\/order-received\/\d+\/\?key=\w+&product_ids=[\w,]*ID[\w,]*

Upvotes: 1

Related Questions