To get insights into user behavior to optimize your site performance you must incorporate advanced analytics & tracking like Google Analytics 4 (GA4), Google Tag Manager (GTM) & Microsoft Clarity on your Drupal site. Find the code based way via 'theme_preprocess_html()' hook in your Drupal theme from this guide so that developers can integrate and put the tracking codes as per their requirement.
1. Google Analytics 4 (GA4) Integration
Google Analytics 4 is the next generation of Google Analytics that includes new features like cross-platform measurement and machine learning-powered insights. In this tutorial, I’ll detail how you can manually integrate GA4 with your Drupal site.
Step 1: Insert the GA4 Tracking Code in theme_preprocess_html()
Step 2: Open your theme’s YOUR_THEME.theme file.
Step 3: Add the following code to inject the GA4 tracking code into the HTML head:
function YOUR_THEME_preprocess_html(&$variables) {
$ga_measurement_id = 'G-XXXXXXXXXX'; // Replace with your GA4 Measurement ID.
$variables['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#attributes' => ['type' => 'text/javascript'],
'#value' => "
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '$ga_measurement_id');
",
],
'google_analytics_4',
];
}
Step 2: Insert Your GA4 Measurement ID for the Placeholder
Take the GA4 Measurement ID you collected, and replace ‘ G-XXXXXXXXXX ’ with it—the ID value is available in the GA4 property settings.
Step 3: Clear Cache and Verify
Clear Drupal’s cache to ensure the changes take effect:
drush cr
Pop in your site and navigate to the Real-time section of your GA4 account to confirm that the tracking code is active.
2. Installation of Google Tag Manager (GTM)
Google Tag Manager helps you deal with multiple tracking codes at once and you do not need to alter the site codes most of the time. Here is method of using GTM with the theme_preprocess_html() hook.
Step 1: Inject the GTM Container Code
In the same YOUR_THEME.theme file, add the following code:
function YOUR_THEME_preprocess_html(&$variables) {
// Google Tag Manager Container ID.
$gtm_container_id = 'GTM-XXXXXX'; // Replace with your GTM Container ID.
// Add GTM script to the head.
$variables['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#attributes' => ['type' => 'text/javascript'],
'#value' => "
(function(w,d,s,l,i){
w[l]=w[l]||[];
w[l].push({'gtm.start': new Date().getTime(), event:'gtm.js'});
var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
j.async=true;
j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','$gtm_container_id');
",
],
'google_tag_manager_head',
];
// Add GTM noscript fallback in the body.
$variables['#attached']['html_head'][] = [
[
'#tag' => 'noscript',
'#value' => "",
],
'google_tag_manager_noscript',
];
}
Step 2: Replace the Placeholder with Your GTM Container ID
Replace 'GTM-XXXXXX' with your actual GTM Container ID. You can find this in your GTM account.
Step 3: Publish Your GTM Container
Go to your GTM account, add any tags you need (like GA4), and publish the container.
Step 4: Clear Cache and Verify
Clear Drupal’s cache:
drush cr
Ensure the GTM container actually fires on your site using GTM preview mode or GTM chrome extension.
3. Microsoft Clarity Integration
Microsoft Clarity gives you session recordings and heatmaps to understand how users interact on your site. You can integrate Clarity directly or through GTM.
Step 1: Add Clarity Tracking Code in theme_preprocess_html()
Add below code in YOUR_THEME.theme file:
function YOUR_THEME_preprocess_html(&$variables) {
$clarity_project_id = 'YOUR_CLARITY_ID'; // Replace with your Clarity Project ID.
$variables['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#attributes' => ['type' => 'text/javascript'],
'#value' => "
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){
(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);
t.async=1;
t.src='https://www.clarity.ms/tag/'+i;
y=l.getElementsByTagName(r)[0];
y.parentNode.insertBefore(t,y);
})(window, document, 'clarity', 'script', '$clarity_project_id');
",
],
'microsoft_clarity',
];
}
Step 2: Replace the Placeholder with Your Clarity Project ID
Replace the YOUR_CLARITY_ID with your original Microsoft Clarity Project ID that can be found at the Clarity Platform.
Step 3: Clear Cache and Verify
Clear Drupal’s cache:
drush cr
Try to navigate through the Clarity dashboard to be sure that data is collected.
Benefits of this integration
- Full usage control:
- Customization: Adding tracking code directly via theme_preprocess_html() gives developers full control over how and where these scripts are loaded.
- Reduce dependency on modules: Avoid additional modules to keep your site lightweight.
- Performance enhancement: Optimize script loading for better site performance.
Flaws of This Integration
- Increased Maintenance Effort: Requires manual updates for tracking codes.
- Potential for Human Error: Mistakes in copying or placing code can lead to failures.
- Limited Flexibility: Hardcoded logic is less adaptable than module-based approaches.
Conclusion
Adding Google Analytics 4, Google Tag Manager, and Microsoft Clarity to your Drupal theme through the theme_preprocess_html() hook offers control and adaptability. However, it requires more effort and is prone to errors. This approach suits developers seeking precision and minimal dependency on third-party modules.