Skip to content

Instantly share code, notes, and snippets.

@wickywills
Last active September 1, 2020 06:35
Show Gist options
  • Save wickywills/1ba8d92787f81d1a062366690164a1dc to your computer and use it in GitHub Desktop.
Save wickywills/1ba8d92787f81d1a062366690164a1dc to your computer and use it in GitHub Desktop.
```
<?php
/**
* Add generic tracking code to all pages except "Thank you" page
*/ ?>
<!-- Global site tag (gtag.js) - Google Ads: 734634785 -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-XXXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);}
gtag('js', new Date()); gtag('config', 'AW-XXXXXXXXXXX');
<?php
if ( is_checkout() && !empty( is_wc_endpoint_url('order-received') ) ) :
global $wp;
$order_id = apply_filters( 'woocommerce_thankyou_order_id', absint( $wp->query_vars['order-received'] ) );
$order = wc_get_order( $order_id );
$order_total = $order->get_total();
$order_currency = $order->get_currency();
?>
gtag('event', 'conversion', {
'send_to': 'AW-XXXXXXXXXXXXXX',
'value': <?php echo $order_total; ?>,
'currency': '<?php echo $order_currency; ?>',
'transaction_id': '<?php echo $order_id; ?>'
});
<?php endif; ?>
</script>
```
Alternatively you can use a hook
```
/**
* Add custom tracking code to the thank-you page
*/
add_action( 'woocommerce_thankyou', 'my_custom_tracking' );
function my_custom_tracking( $order_id ) {
// Lets grab the order
$order = wc_get_order( $order_id );
/**
* Put your tracking code here
* You can get the order total etc e.g. $order->get_total();
*/
// 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 );
// This is the products SKU
$sku = $product->get_sku();
// 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 );
}
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment