Set Google conversion tag event code values in Woocommerce order received page

Viewed 2500

I am trying to install the Google Adwords Conversion tag into Wordpress; specifically Woocommerce. We have tried plugins, but had conflicts with other items so we are now trying to manually implement it.

We have the following 'event' tag placed in our functions.php file:

add_action( 'woocommerce_thankyou',    'conversion_tracking_thank_you_page' );

function conversion_tracking_thank_you_page() {
?>
<!-- Event snippet for Transaction conversion page -->
<script>
 gtag('event', 'conversion', {
  'send_to': 'AW-######/######',
  'value': 1.0,
  'currency': 'USD',
  'transaction_id': '
 });
</script>
<?php
}

It pulls correctly, but, all transactions default to $1. We have this set to revert to $1 if there is no transaction value, however we want to pull the transaction value from Woocommerce. I have searched everywhere, and cannnot find the correct code for the event tag specifically, to pull this value from Woocommerce.

1 Answers

Updated

Try the following (where you will have to set the correct 'send_to' replacing 'AW-######/######'):

add_action( 'woocommerce_thankyou', 'conversion_tracking_thank_you_page', 95, 1 );
function conversion_tracking_thank_you_page( $order_id ) {
    if( ! $order_id )
        return;

    // Get the WC_Order instance Object
    $order = wc_get_order( $order_id ); 
    ?>
    <!-- Google Tag: Transaction conversion event -->
    <script>
    gtag('event', 'conversion', {
      'send_to'       : 'AW-######/######',
      'value'         : <?php echo $order->get_total(); ?>,
      'currency'      : '<?php echo $order->get_currency(); ?>',
      'transaction_id': <?php echo $order->get_transaction_id() ? $order->get_transaction_id() : $order_id; ?>
    });
    </script>
    <?php
}

Code goes in function.php file of your active child theme (or active theme). Tested output… It should works this time.


Similar answers:

Related