Google Ads Conversion Tracking for WooCommerce
Loads the Google Ads tag and reports a purchase conversion with the order value and transaction ID on the WooCommerce order received page.
Opens WPIDE on
Code
$wpide_gads = array(
'conversion_id' => 'AW-XXXXXXXXX', // Your Google Ads tag ID.
'conversion_label' => 'XXXXXXXXXXXXXXXX', // Conversion label of the purchase action.
);
add_action( 'wp_head', function () use ( $wpide_gads ) {
if ( 'AW-XXXXXXXXX' === $wpide_gads['conversion_id'] ) {
return;
}
printf(
"<script async src=\"%s\"></script>\n<script>window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', %s);</script>\n",
esc_url( 'https://www.googletagmanager.com/gtag/js?id=' . rawurlencode( $wpide_gads['conversion_id'] ) ),
wp_json_encode( $wpide_gads['conversion_id'] )
);
}, 5 );
add_action( 'woocommerce_thankyou', function ( $order_id ) use ( $wpide_gads ) {
$order = wc_get_order( $order_id );
if ( 'AW-XXXXXXXXX' === $wpide_gads['conversion_id'] || ! $order || $order->get_meta( '_wpide_gads_sent' ) ) {
return;
}
$data = array(
'send_to' => $wpide_gads['conversion_id'] . '/' . $wpide_gads['conversion_label'],
'value' => round( (float) $order->get_total(), 2 ),
'currency' => $order->get_currency(),
'transaction_id' => (string) $order->get_order_number(),
);
echo "<script>if (typeof gtag === 'function') { gtag('event', 'conversion', " . wp_json_encode( $data ) . "); }</script>\n";
$order->update_meta_data( '_wpide_gads_sent', time() );
$order->save();
}, 20 );
Notes
Set $conversion_id (AW-...) and $conversion_label from Google Ads > Goals > Conversions. Nothing is output while the placeholders are in place.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.