Google analytics conversion v4

Verze:

01. 09. 2022

Zodpovědná osoba:

Dominik Šlechta

For GA4 conversions you first need to find out and possibly secure the GA4 entry in @layout.latte, see here for how to do that: https://wiki.czechgroup.cz/cs/m-210

 

The following code is taken from cykloanimal.cz

Conversions are always sent only on the page after the order is placed and the order information is sent to google.

The process of adding:

  • It is necessary to add to final.latte in block scripts and to the subcondition that looks similar to the one below
     $orderId != 'nofound' && $isProduction && $diff < 5

    the following code

    {if isset($web['GOOGLE_ANALYTICS']) && strlen($web['GOOGLE_ANALYTICS']) > 1 && (isset($cookieSettings, $cookieSettings['cookie_analytics']) || !isset($cookieSettings))}
      <script type="text/javascript">
      // Google Analytics - Ecommerce modul
      gtag('event', 'purchase', {
        'transaction_id': "{$order['id']|noescape}",
        'affiliation': {$order['shopname']},
        'value': "{$order['total_sum']|number:2:'.',''|noescape}",
        'currency': {$order['currency']},
        'tax': "{$order['tax_sum']|number:2:'.',''|noescape}",
        'shipping': "{$order['shipping_sum']|number:2:'.',''|noescape}",
        'items': [
          {foreach $order['products'] as $product}
          {
            'id': "{$product['product_id']|noescape}",
            'name': {$product['name']},
            'quantity': "{$product['piece']|number:0:'.',''|noescape}",
            'price': "{$product['price']|number:2:'.',''|noescape}",
          }
          {sep},{/sep}
          {/foreach}
        ],
      });
      </script>
    {/if}
  • Then you need to modify GOOGLE_ANALYTICS to the type that is set for the condition of initializing google analytic in @layout.latte.

 

This can only be tested by changing the GOOGLE_ANALYTICS language to some nonsense (there must be at least 2 characters filled in) and then putting the code above outside the condition in the first code block. I open the explorer and check that it contains the data it should.

 

If this is to be solved in a task (ask in the task if it is not mentioned), the conversion code is also supplied (meaning the code below). It is inserted into the site configuration as follows:

<script>
  gtag('event', 'conversion', {
      'send_to': 'konverzni kod', // a fixed code is given
      'value': ###VALUE_VAT###, // total price of the order
      'currency': '###CURRENCY###', // currency
      'transaction_id': '###ORDERID###' //order id
  });
</script>

It is necessary to verify that the placeholders in basket.php are changed to the correct data and modify basket.php if necessary.
And test it again.