Adding Tracking Scripts to Your Craft Site

“I don’t see anywhere in Craft to put tracking scripts. How do I do that?”

This question gets asked very often by website owners, marketing managers, and other folks in non-developer roles. The short answer is that you’ll need to reach out to the developers of your website. Craft, as a blank canvas CMS, provides no content or template editing capabilities that your developers don’t create for you in the Control Panel.

It’s a good idea to restrict the ability to add scripts. Tracking and advertising scripts can increase page load times which in turn, negatively effects SEO rankings. From a security perspective, anyone with permission can add nefarious scripts intentionally, or even unwittingly.

With that said, there are three common ways to embed scripts in your Craft site.

Adding scripts to templates #

Most often, scripts are added directly to template files. These template files live on the server that hosts your website and need to be accessed via FTP or SSH. The risk is that if you add any malformed HTML or JavaScript, your site could break.

The topic of how to use FTP or SSH to edit files on your server is outside the scope of this guide. Some web hosting providers offer a way to edit files from their dashboard as an alternative.

You will find template files in the templates/ directory. Template structures vary in complexity from site to site, so we can’t tell you precisely which templates to locate. It’s very common to find a directory named layouts or files named like _layout.html. You’re looking for templates that have the <head> and <body> tags you were instructed to find. Paste your embed code there then save the files. If there are more than one or two layout templates, you might need to test by trial and error.

Adding scripts from the Control Panel #

You can ask your developer to create a global field for you to add and remove scripts as needed. This is a common feature request from tech-savvy content editors. Again, the risk is that malformed code entered in these fields can break the website. You’ll want to restrict permissions to these fields.

Adding scripts with tag managers #

A great way to manage scripts on your site is with a service like Google Tag Manager; often referred to as GTM. Services like GTM allow your developer to add a single script to your website; one script to rule them all. Then, anyone with permissions to access your GTM dashboard can add custom scripts there as well as specify conditions and rules for when they should be included. Scripts are then injected into your web pages by GTM, not by Craft.

The topic of how to use Google Tag Manager is outside the scope of this guide, but a Google search will bring up many tutorials and training videos.

Applies to Craft CMS 3 and Craft CMS 2.