Add Google Analytics Tracking Code Using WordPress Hook

Forget the old fashion way of adding Google Analytics tracking code directly in footer.php or header.php of your WordPress website! We’re going to add the tracking code using WordPress hook.

To make it work, add this codes to your functions.php file.

<?php
function risbl_analytics() {
?>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR-TRACKING-ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-233930942-1');
</script>

<?php
}
add_action( 'wp_head', 'risbl_analytics', 99 );
?>

Don’t forget to replace YOUR-TRACKING-ID text with your Google Analytics tracking ID.

 103 total views,  2 views today

Leave a Comment

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