Track Number of Search Results in Google Analytics with GTM

Tracking the number of onsite search results is useful for finding common searches for which few, or zero, results were returned, so that you can address gaps in your product or content offerings. This metric can also be used to analyze the correlation between search result counts and conversion rates. While the built-in onsite search report in Google Analytics contains many useful metrics for understanding the search-related behavior of users on your website (search refinements, search depth, search terms, etc.), it doesn't include the number of returned search results. Therefore this blog post will walk through how to track the number of onsite search results in Google Analytics (GA) using Google Tag Manager (GTM) and a custom metric.

This post assumes you have already configured GA's built-in onsite search tracking using query parameters in the URL (documentation). If not, you'll need to do that first.

STEP 1 (OPTIONAL): PUSH THE NUMBER OF SEARCH RESULTS INTO THE DATA LAYER

The most robust method of tracking search results is to have your developers push information to a data layer using the following syntax (the exact event names and keys can differ):

dataLayer.push({
 'event': 'searchResults',
 'numSearchResults': $search_results //the actual number would be dynamically updated here, e.g. 56
 });

This step is marked as optional (but recommended!) because an alternate method is to scrape the number of search results from the page itself, bypassing the need for a data layer. Step 2 has more information on that.

STEP 2: CREATE A GTM VARIABLE CONTAINING THE NUMBER OF SEARCH RESULTS

If your developers have added search results into the data layer, you next pass these values into GTM by clicking Variables > User-Defined Variables > New >  Variable Type = Data Layer Variable. Set up a variable containing the key (in this case 'numSearchResults') from the data layer push.

number-search-results-img1

❓If you do NOT have a data layer to work with, you can usually get the number of search results from the page itself, using a little Javascript in GTM to scrape the DOM. This is the quick & dirty method, subject to break if/when the page structure changes. DOM scraping is terrible, do not do this....but if you must, it is very powerful 😅.  Here's an example of how this works using Amazon.com. For this example, I've searched for "red hats", returning 243,059 results.

number-search-results-img4

Opening up Developer Tools and inspecting the element shows that the value is located inside id = "s-result-count"

number-search-results-img5

Recognizing that the search results are surrounded by the text "of" and "results" we navigate in GTM to Variables > User-Defined Variables > New > Custom JavaScript and create a script to parse the value out:

function(){
 if(document.querySelector('#noResultsTitle')){
   return 0;
 } else {
   var str = document.querySelector('#s-result-count').innerText;
   var posStart =str.search("of");
   var posEnd =str.search("results");
   var resultsString = str.substr(posStart+3,posEnd-9);
   return resultsString.replace(/,/g, '');
 }
}

The first part of the script returns 0 if there are zero search results, while the second part returns the number of search results if there are any. Here's a good place to point to the post that inspired this one, showing a similar example of tracking zero search results. It's worth checking both posts since they demonstrate two different approaches (passing the information in an event vs. a custom metric)

Finally: if the website is using single page app technology and you're triggering page views off a history change listener, you're likely to run into race conditions where the text you're scraping isn't yet available at the time the page view tag fires. You can resolve this by creating a delayed history change event in a custom HTML tag, and firing the page view off that delayed event trigger instead:

 

STEP 3: CREATE A CUSTOM METRIC

In GA, navigate to Admin > Property > Custom Definitions > Custom Metrics > + NEW CUSTOM METRIC and fill out the following details with Scope - Hit and Formatting Type = Integer.

number-search-results-img2

After hitting Save, note the automatically assigned index number, as you'll need that later.

number-search-results-img3

STEP 4: ADD THE CUSTOM METRIC TO A PAGEVIEW TAG

Custom metrics need to be attached to other hits, like pageviews or events. You can check this post for more details on custom metrics: Add Custom Metric to GA Using Google Tag Manager. 

In this case, we'll add the custom metric to the main Google Analytics page view tag, which is usually set to fire on every page. In the page view tag, click Enable overriding settings in this tag, navigate to the Custom Metrics section, and fill in the Index with the index number assigned in step 3 and the Metric Value with the variable you created in step 2. (Alternately you can set it using the Google Analytics Settings variable.)

number-search-results-img6

You can add it to the main pageview tag even though the value is specific for search results pages. This is because if the value is undefined, it just won't get sent to GA.

STEP 5: PUBLISH THE TAG

Always preview and test before publishing.

STEP 6: CREATE A CALCULATED METRIC

Since the custom metric automatically sums itself, by default it will show you the total number of search results for that term, across all sessions and users. To see average number of search results returned each time, set a calculated metric using the formula {{Search Results}} / {{Total Unique Searches}} , where {{Search Results}} is the new custom metric set above.

number-search-results-img9

STEP 7: CREATE A CUSTOM REPORT

Following this onsite search results implementation, you will be pushing the number of search results into a custom metric tied to the page view tag. Search terms are automatically collected from the page view tag, so this method will let you link search terms and search results together. As it's not a default report, you will need to create a custom report, choosing Dimension = Search Term, Metric = Avg Search Results, and any other search-related metrics you're interested in.

number-search-results-img7

CONCLUSION

This setup allows us to see search results (and other search metrics) for search terms. Using the excellent Tag Manager Injector plugin, I ran some searches on Amazon's site, using my own GTM container. Here you can see the results after tying everything together: a new "Avg Search Results" metric tied to Search Terms.

number-search-results-img8

5 thoughts on “Track Number of Search Results in Google Analytics with GTM”

  1. I would like to collect search results when customer search a product . let's say apple. search result show 4 products. and this number(search results) can not be changed in GA right? however it changed weird..

    • If there are 4 search results, you should pass '4' into a custom metric using the techniques described above. This number won't change once it's collected by GA.

      • All tags need a trigger to fire. The above article suggests attaching your custom metric to the main pageview tag, which usually has a trigger to fire on every page.

Comments are closed.