WooCommerce Order Confirmation script

Overview

WooCommerce does not expose order variables in Javascript, so in order to track the sales, you will need to implement a PHP script which captures the variables into Javascript.

This will also require the site-wide script from the standard Tracking Integration Guide.

We highly recommend using a tag manager, or a 3rd party plugin to assist in adding the code.

Script

This script may require some customization for your WooCommerce version. This has only been tested with version 3.0 so far.

function avantlink_tracking( $order_id ) { 
$order = wc_get_order($order_id); 
$subtotal = $order->get_subtotal() - $order->get_total_discount();

$items = $order->get_items(); 
$abc = count($items); 
$arr_sc = array(); 
$i = 0; 
$j = 0; 

foreach ($items as $item) { 
$arr_sc[$i][$j++] = $order_id; 
$product_id = $item['product_id']; 
$arr_sc[$i][$j++] = $itm_total = $item['total']; 
$arr_sc[$i][$j++] = $product_qty = $item['qty']; 
$product_variation_id = $item['variation_id'];

// Check if product has variation. 
if ($product_variation_id) { 
$product = new WC_Product_Variation($item['variation_id']); 
$parentsku = $product->parent->sku; 
} else { 
$product = new WC_Product($item['product_id']); 
}

// Get SKU 
$arr_sc[$i][$j++] = $sku = $product->get_sku(); 

if($parentsku){ 
$arr_sc[$i][$j++] = $parentsku ; 
}else{ 
$arr_sc[$i][$j++] = $sku; 
} 
$i++; 
$j=0; 
} 
?> 
<script> 
var AvantMetrics = AvantMetrics || []; 
window.onload = function(){ 

_AvantMetrics.push(['order',{ amount:'<?php echo $subtotal; ?>', country:'<?php echo $order->billing_country; ?>', order_id: '<?php echo $order_id; ?>', 
state:'<?php echo $order->billing_state; ?>'}]); 

var jsfiles = <?php echo json_encode($arr_sc) ?>; 

for (i = 0; i < <?php echo $abc; ?>; i++) { 
_AvantMetrics.push(['item',{ order_id: '<?php echo $order_id;?>', price:jsfiles[i][1], qty:jsfiles[i][2], variant_sku:jsfiles[i][3]}]); 
/*_AvantMetrics.push(['item',{ order_id: '<?php echo $order_id;?>', parent_sku:jsfiles[i][4], price:jsfiles[i][1], qty:jsfiles[i][2], variant_sku:jsfiles[i][3]}]);*/ 
} 

}; 

</script> 
<?php 
} 
add_action( 'woocommerce_thankyou', 'avantlink_tracking');

 

Have more questions? Submit a request
Powered by Zendesk