Blog overview

Craft CMS: Control your tracking codes from the control panel

We launch a new website, and shortly before we go online, the question of whether the Google Analytics code is implemented comes up. It's not a problem at all, but it’s usually not just the Google Analytics tracking code. Maybe you need services like Hotjar or something else. Including codes from services like this without touching the code itself would be nice. Here is a solution.

What we need:

 Let’s create our fields

We control this in the Globals. We just need a SuperTable field with three subfields. 

  • Snippet Name: It is not important just to show the User in the CP what code it is without searching within the code itself.
  • Snippet Status: To active / deactivate the Code
  • Snippet Code: The code itself

Here is the Code to create the Fields:

In short: It creates the SuperTable field and the global. You can paste this code in the „Raw Input“ Field in „The Architect“ or make it on your own when you don’t have installed The Architect Plugin.

Now it just looks like this:

Craftcms thirdparty snippets 01

Add the Twig Code

Now, we must include the code for this in our twig templates. I’ve included it in the _scripts.html file, which is included in the footer. 

Here is the snippet:

We simply check if the global field exists, and then we loop over the content to include all the codes.

Add a code

Now, you can add codes in the CP and activate them whenever possible. You can also sort the different codes.

Here is Hotjar as an example:

Craftcms thirdparty snippets 02

And after activation, it must look like this:

Craftcms thirdparty snippets 03

That’s it! Any suggestions?