Woocommerce + Enhanced Ecommerce

If you’re like me, structured data causes severe eye roll and an immediate tuneout. However, we’re sometimes asked to do things we hate. Such was the case when a client wanted to implement Google Analytics Enhanced Ecommerce on their site.

The implementation on product and checkout pages was fairly straightforward, but we had a few issues with checkout tracking. If you’re having the same problem, pop this into your functions.php. This doesn’t include purchase totals but does include coupons, so you can tweak as needed.

The core code is from Woocommerce but this includes the full variable set so you’ll be tracking your checkouts in no time.

<?php
function thank_you_conversion_tracking($order_id) {
  $order = wc_get_order($order_id);
  $coupons = $order->get_used_coupons();
  $code = implode(',',$coupons);
  
  // This is the order total
  $order->get_total();
 
  // This is how to grab line items from the order 
  $line_items = $order->get_items();

  // This loops over line items
  foreach ( $line_items as $item ) {
  // This will be a product
  $product = $order->get_product_from_item( $item );
    
    $name = $product->get_title();
  
    // This is the products SKU
    $sku = $product->get_sku();
    
    // This is the products Price
    $price = $product->get_price();
    
    // This is the qty purchased
    $qty = $item['qty'];
    
    // Line item total cost including taxes and rounded
    $total = $order->get_line_total( $item, true, true );
    
    // Line item subtotal (before discounts)
    $subtotal = $order->get_line_subtotal( $item, true, true );
  }
  ?>
  
  <script>
  ga('create', 'UA-XXXXXXXXX-X'); // Your GA code
  ga('require', 'ec');
  
  ga('ec:addProduct', {
  	'id': '<?php echo $sku; ?>',
  	'name': '<?php echo $name;  ?>',
  	'brand': 'Brand name', // Your brand or a custom variable
  	'price': '<?php echo $price; ?>',
  	'quantity': '<?php echo $qty; ?>'
  });

  // Transaction level information is provided via an actionFieldObject.
  ga('ec:setAction', 'purchase', {
  	'id': '<?php echo $order_id; ?>',
  	'affiliation': 'Store Name', // Your Store Name
  	'revenue': '<?php echo $order->get_total(); ?>',
  	'coupon': '<?php echo $code; ?>'    // User added a coupon at checkout.
  });

  ga('send', 'pageview');     // Send transaction data with initial pageview.
  </script>

<?php 	
}
?>

 

 

Share on facebook
Share
Share on twitter
Tweet
Share on linkedin
Share
Share on pinterest
Pin

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Other Stuff You Might Like

Looking for Hosting?

Stafford Creative uses and recommends Siteground for fast, reliable hosting for every project and budget.

*Stafford Creative may receive a small commission with each signup.