1

My client has asked that I track and send campaign information through a contact form.

So basically a user might come to the site on this type of URL:

domain.com/?utm_source=Facebook&utm_medium=social&utm_campaign=paid16-03-2022

I can certainly get the query string information into a form (if they come directly to the form page) but if they go to multiple other pages and then fill in the form it gets a little more difficult to track.

My thinking was to:

  • Set a cookie to capture the query string variables when they come to the site
  • Put these cookie variables into a hidden contact form field/s (if they go to this page)

I just wanted to double-check if this is the best way, if anyone had done this before or if there was a plugin or something else to help?

2

Yes, you can do something like that. I built something very similar a few months ago where I checked for a query parameter in the URL when the page loaded, created a cookie with it using the Cookies plugin so I could access it in twig, then appended that query parameter to a donation button on other pages.

Cookies: https://plugins.craftcms.com/cookies

You also need to check if the parameter has changed or disappeared, and update or replace your cookie value accordingly. Some of the code I used is below.

_layout.twig:

{# User Tracking #}
    {% if craft.app.request.getParam('s_src')|length %}
        {# If a user lands on the site with s_src in the URL, set a variable to track them throughout the site #}
        {% set s_src = craft.app.request.getParam('s_src') %}

        {# Use that variable to set a cookie, which will track them between pages #}
        <script>
            document.cookie = "userSrc={{ s_src }}; Path=/; expires={{ now|date_modify('+1 day')|date('l, d-M-Y H:i:s T') }}";
        </script>
    {% else %}
        {# If there isn't an s_src param in the URL, clear the variable, but still define it so Craft doesn't crash #}
        {% set s_src = '' %}
    {% endif %}

content block:

{# If there's an s_src param in the URL, use that. If there isn't, check for the cookie and use that. If there isn't one, use the defaultSessionVariable #}
<a href="{{ block.button.url }}{{ '?' in block.button.url == 0 ? '?' }}&s_src={% if s_src|length %}{{ s_src }}{% elseif getCookie('userSrc') %}{{ getCookie('userSrc') }}{% else %}{{ block.defaultSessionVariable }}{% endif %}" class="bg-{{ block.buttonColor }} c-white btn-lg button-block" aria-label="{{ block.button.text }}" target="{{ block.button.target }}">{{ block.button.text }}</a>

If you're in the UK, Europe or California, you'll need to comply with the GDPR / CCPA legislation on cookies.

1
  • Thanks Daryl, thats fantastic - I will give it a try shortly – Malcolm Maclean Mar 27 '20 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.