Analytics: Add Microsoft Clarity Tracking Script to WordPress

Analytics add microsoft clarity tracking script to wordpress image

Clarity is actually pretty cool. I never end up looking at it or pulling useful info from it. But you COULD!

What it does…

Adds the Microsoft Clarity tracking script to your site. NOTE: You’re gonna wanna add your own unique MS Clarity Project ID in the code, then let this snip take care of the rest.

How it does it…

Adds the tracking JavaScript code to the head of your site using `wp_head`, but only on Production (if using Env555), and only for logged-in users. (But you could edit those parts, if desired.)

See the code…

<?php

// Analytics: Add Microsoft Clarity Tracking Script to Wordpress
// https://snipsnip.pro/s/171
/* Uses Env555, if available */
namespace McIKEpQO;

\add_action( 'wp_head', function () { 
    
	$msID = "XXXXXXXXXXXX";
    
	$addCode = true;
	if (function_exists('\Env555\this_is_a_production_site')) { 
	    // only on production for logged out users
    	$addCode = (\Env555\this_is_a_production_site() && !\is_user_logged_in());
	}
	
	if ($addCode === true) {
?>

<!-- Analytics: Add Microsoft Clarity Tracking Script to Wordpress - https://snipsnip.pro/s/171 -->
<script>
    (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", "<?php echo $msID; ?>");
</script>

<?php } }, 1000 );