• Courses
    • Courses
    • Course bundles
  • Blog
  • Services
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • About
    • About
    • Contact
  • Login
  • Courses
    • Courses
    • Course bundles
  • Blog
  • Services
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • About
    • About
    • Contact
  • Login

February 1, 2020

How to Extract a Query Parameter with Google Tag Manager

Google Tag Manager can help you do a lot of useful things and extracting query parameters is one of them. If a URL of the page contains a query parameter (it comes after the question mark in the address), you can turn that into a variable in Google Tag Manager and reuse in tags, triggers or even other variables. In today’s guide, I’ll show you several examples of how to extract query parameters in GTM.

Google Tag Manager Ebook Bundle

What is a query parameter?

Before we continue, first let’s have a quick reminder of (or maybe learn?) what query parameters are in general. Query parameter (also known as a query string) is a part of the URL that assigns values to specified parameters.

Typical URL example with the query parameter can look like this:

https:///www.analyticsmania.com/search?keyword=google+tag+manager

In the case above, the query parameter is “keyword” and its value is “google+tag+manager“. Speaking of web tracking, one of the most popular (if not the most popular) query parameters are UTM parameters. If you want to track the impact of your digital marketing campaigns, you can add UTMs to your links (e.g. utm_medium or utm_source) and Google Analytics will automatically catch them, attributing the session to that particular traffic source.

However, it’s very common for websites to use other query parameters that are necessary for websites/apps to work and coincidentally, you might want to use those query strings in your GTM setup as well. For example, maybe a URL contains a parameter called product_id that you would like to use as a custom dimension and pass to Google Analytics?

With Google Tag Manager, that is not a problem. Continue reading and I’ll show you how to do that.

 

Prefer videos? Here’s a tutorial

But if you want learn even more details about this technique, I highly recommend to read this entire blog post too.

 

How to extract a query parameter of the current page URL

Google Tag Manager has a neat feature called URL Variable. It can return a value of a particular query parameter that is currently in the URL. So if a URL indeed contains, say, a product ID (https://www.analyticsmania.com/products?product_id=12345), with that variable, you could actually fetch and get the value of “12345”.

If you want to extract a query parameter with Google Tag Manager, go to your GTMr container > Variables > New (in the User-defined variables section). Enter the following settings:

  • Variable type: URL
  • Component type: Query
  • Query key: product_id (you should enter here the name of the actual query string you want to get)

Save the variable, enable the Preview and Debug mode, refresh the web page of your site that you’re currently working on (with the query string in the URL) and check the Variables tab. In it, you should find your recently created URL variable that returns the value of the query parameter.

If you want to learn more about other Component Types of the URL variable, read this guide.

Where else would you need to extract a query parameter?

If you’re interested in other use cases of this variable, here is some food for thought. I’ve used this variable in various situations, e.g.:

  • Track affiliate sales with Google Tag Manager
  • Transfer UTM parameters from one page to another

 

How to extract a query parameter of the clicked URL (or any other URL)

Another cool feature of the URL variable in GTM is that you can work not only with the URL of the current page (because that’s how the variable works by default). In fact, you can use any variable as an input.

For example, if you want to extract a query parameter of a clicked link, you can do that by completing the following actions:

  • In the URL variable, expand More Settings section
  • And choose the {{Click URL}} as a URL source.

In this example, you should use the Click URL variable.

That’s it! Now this variable will return the product_id query string of the clicked URL (if that link actually contains the parameter). If the query parameter is not present, the URL variable will return undefined.

 

If you want to extract ALL the query parameters that are in the URL

If for some reason, you need to extract all the query parameters of the URL and have them as a single variable, you can use the JavaScript variable type of Google Tag Manager (because URL variable can return the value only of a single parameter).

Go to Variables > New (in the User-defined variables section) and choose JavaScript variable. Enter document.location.search.

This will return all the query parameters that are present in the URL (including the leading question mark). Like this:

?product_id=1234&category_id=2222

If you don’t want to have that question mark in the variable, you can use this Custom JavaScript variable instead.

function() {
  return document.location.search.split('?')[1];
}

This will return the same value except for the first question mark, product_id=1234&category_id=2222.

 

If you want to extract a part of Page Path

In this blog post, I’ve explained how to extract query parameters (the part that comes in the URL after a question mark). But what if you want to explain the part after the domain but between two slashes?

For example, you have a URL https://www.example.com/page/category/product

And let’s say that you want to access only the “category”. If that is what you’re interested in, read this guide.

 

How to extract a query parameter with Google Tag Manager: Final Words

In this quick guide, you have learned how to use the URL variable (or other alternatives) in order to extract a query string with the help of Google Tag Manager. Just keep in mind that if you have a choice between using a URL Variable or some custom code, always go with the built-in GTM functionality (in this case, URL Variable). Google Tag Manager developers do a really good job creating optimized built-in features.

By the way, URL Variable is very versatile and can retrieve not only query parameters. You can also get the value of URL fragment, hostname, etc. Just choose a different Component Type in the variable’s settings.

Julius Fedorovicius
In Google Tag Manager Tips
15 COMMENTS
Moshe Yuval
  • Dec 18 2019
  • Reply

Awesome. Simple. Clear

Luis
  • Mar 10 2020
  • Reply

Do you know if there is a way to track query keyword parameters from a POST request? My site doesn't have the query parameters appended to the URL.

    Julius Fedorovicius
    • Mar 11 2020
    • Reply

    It is impossible for JavaScript to access POST request's data (because that request is server-side). Therefore, GTM cannot access values in the POST.

Ian Pegg
  • Aug 7 2020
  • Reply

Every time I have a query about Google Tag Manager Julius has the answer! Thanks for your help yet again buddy!

Justin Karl
  • Aug 18 2020
  • Reply

Thank You!

Now that I have created the variable, and can see it in Preview, is there a way that I can now use it as a reporting metric in GA?

    Julius
    • Aug 18 2020
    • Reply

    How do you want to use it?

      Justin Karl
      • Aug 18 2020
      • Reply

      My most basic need would be a count of sessions listed by each variable value in a given period of time.

      I'd basically like to use it similarly to utm_campaign as an example.

        Julius Fedorovicius
        • Aug 20 2020
        • Reply

        Use GA Custom Dimensions for that.

Jason
  • Sep 15 2020
  • Reply

Hi Julius,

Very clearly explained! What I was wondering: what if I want to separate the parameters? Like if I want ?product_id=1234&5678 to return 2 values (as events/actions) 1234 and 5678 (instead of returning 1 value: 1234&5678)?

Any ideas on that?

    Julius Fedorovicius
    • Sep 16 2020
    • Reply

    How exactly formatted do you want this to be? Because one variable can return a string, it can return an array (e.g. ['1234', '5678']). Or do you need to separate variables? What if the URL variable contains three values?

      Jason
      • Sep 16 2020
      • Reply

      Yes, I need to separate the variables from the url and it can be 3 or more in the same url as well. The values are strings.

      In the end I want to use every single variable as an event action.

        Julius Fedorovicius
        • Sep 16 2020
        • Reply

        1. You cannot automatically create multiple variables. So if the number of parameters can differ, you cannot have a changing number of variables.

        2. Event action in GA does not accept multiple different values. It accepts only strings. So if you send an event when multiple products are purchased, all of the product IDs must be stored in the same field.

        3. If you are trying to implement here sales tracking, event tracking is not built for that. Use Standard Ecommerce https://www.analyticsmania.com/post/ecommerce-tracking-with-google-tag-manager/ or Enhanced Ecommerce.

          Jason
          • Sep 16 2020

          Thank you for your answer Julius!

          Too bad, I was hoping there was a solution I couldn't think of. Maybe try putting every value in an array and in some way get every single value in the array to separate categories/action. I was as far as getting it in an array, but could only get one variable out of it to use in a action:
          function () {
          var value={{VAR newsletter parameter}}.split(",");
          return value[0].trim();

          }
          I wanted to measure newsletter subscriptions, multiple are possible to be selected in the form.

          Thanks again!

          Julius Fedorovicius
          • Sep 16 2020

          Event actions or categories (or other fields) do not accept arrays. Only strings. One event = one event action and one event category. The only thing that accepts arrays is e-commerce tracking.

Najae
  • Apr 5 2022
  • Reply

Hello, Thank you for the valuable info. I do have one inquiry. What if the url does NOT contain the query params and the options on that page seem to be embedded by a third party in an iFrame or somehow un-intentionally hidden? Please advise on this one.

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *

 

Hi, I'm Julius Fedorovicius and I'm here to help you learn Google Tag Manager and Google Analytics. Join thousands of other digital marketers and digital analysts in this exciting journey. Read more
Analytics Mania
  • Google Tag Manager Courses
  • Google Tag Manager Recipes
  • Google Tag Manager Resources
  • Google Tag Manager Community
  • Login to courses
Follow Analytics Mania
  • Subscribe to newsletter
Recent Posts
  • How to Track Gravity Forms With Google Tag Manager: Complete Guide
  • Introduction to Google Tag Manager Server-side Tagging
  • 3 Ways to Pull Data from Data Layer with Google Tag Manager
Analytics Mania - Google Tag Manager and Google Analytics Blog | Privacy Policy
Manage Cookie Settings