Let’s implement Google Tag Manager into Spree

Reading Time: 2 minutes

Before we start, I want to talk a little bit about Google Tag Manager, as shown in the Google Tag Manager page:

Google Tag Manager is easy, free, and reliable. It gives marketers greater flexibility, and it lets webmasters relax and focus on other important tasks.

As you know, if you use Google Tag Manager you are able to measure traffic and visitor behavior, and understand the impact of online advertising and social channels. Pretty useful stuff, right?

So after that little introduction, let's take advantage of using Google Tag Manager within your Spree Store.

The first thing you have to do, is create a new Deface Override file to add the Google Tag Manager partial into the main spree_application layout.

Where "add_google_tag_manager" can be whatever name you want.

app/overrides/spree/layouts/spree_application/add_google_tag_manager.html.erb.deface

The override's content file is:

<!-- insert_after '.container' -->
<%= render :partial => 'spree/shared/google_tag_manager'%>

Create a new partial for Google Tag Manager in the following location:

app/views/spree/shared/google_tag_manager.html.erb

And add the following code inside that partial:

<!-- Google Tag Manager -->
<noscript>
  <iframe src="//www.googletagmanager.com/ns.html?id=<%= ENV['GOOGLE_TAG_MANAGER'] %>"
height="0" width="0" style="display:none;visibility:hidden">
  </iframe>
</noscript>
<script>
  dataLayer = [];
  (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
  '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer','<%= ENV['GOOGLE_TAG_MANAGER'] %>');
</script>
<!-- End Google Tag Manager -->

<%= javascript_tag do %>
  <% if @order.present? and @order.email.present? %>
     dataLayer.push({'transactionEmail': '<%= @order.email %>'});
  <% end %>
  <% if @order.present? and @order.user.present? %>
     dataLayer.push({'userid': '<%= @order.user.id %>'});
  <% end %>

  <% if flash[:commerce_tracking] and @order.present? %>

     dataLayer.push({
       'transactionId': '<%= @order.number %>',
       'transactionAffiliation': 'Yourcompanyname',
       'transactionTotal': <%= @order.total %>,
       'transactionTax': <%= @order.adjustments.tax.sum(:amount) %>,
       'transactionShipping': <%= @order.adjustments.shipping.sum(:amount) %>,
       'transactionCity': '<%= @order.bill_address.city %>',
       'transactionState': '<%= @order.bill_address.state_text %>',
       'transactionZip': '<%= @order.bill_address.zipcode %>',
       'transactionEmail': '<%= @order.email %>',
       'transactionProducts': [
          <%= raw @order.line_items.map do |line_item|
            "{
              'sku': '#{h line_item.variant.sku}',
              'name': '#{h line_item.variant.product.name}',
              'category': '',
              'price': #{h line_item.price},
              'quantity': #{h line_item.quantity}
            }"
          end.join(",") %>
        ]
     });

  <% if @order.user.present? and @order.user.orders.complete.count==1 %>
     dataLayer.push({
       'event': 'first_time_user_conversion'
     });
   <% end %>
  <% end %>
<% end %>

Last thing to do, is export your environment variable "GOOGLE_TAG_MANAGER"

export GOOGLE_TAG_MANAGER=GTM-heridev

Or, if you are using the Figaro gem you have to add it to your application.yml; for instance:

development:
  GOOGLE_TAG_MANAGER: 'GTM-heridev'

And that should take care if it. Easy stuff.

Shout out and thanks to @neddenriep on github.com for the reference code :).

Any comments or questions you may have, please write them at the comments section below.

Thanks for reading!

H.

0 Shares:
You May Also Like
Read More

3 ecommerce platforms for retailers

Reading Time: 2 minutes Non-store retailing continues strengthening worldwide, and according to Euromonitor analyst, Amanda Bourlier, in 2021 sales for more than…