WP SITES

2952 Tutorials & 191 Plugins

Load Google Analytics Tracking Script From Your Functions File

This tutorial provides both the sample.js file and PHP code which enable you to load your tracking script from your functions file.

This way you have total control over both which pages you want tracked and the position the script loads on the page.

There’s 2 simple steps to take:

Script Within Hook

You can also add your Google Analytics tracking script directly within a WordPress hook like this :

add_action('wp_footer', 'wpsites_googleanalytics');
function wpsites_googleanalytics() { ?>

	<!-- Google tag (gtag.js) -->
	<script async src="https://www.googletagmanager.com/gtag/js?id=G-5DGL9SCY96"></script>
	<script>
	  window.dataLayer = window.dataLayer || [];
	  function gtag(){dataLayer.push(arguments);}
	  gtag('js', new Date());

	  gtag('config', 'G-5DGL9SCY96');
	</script>

    <?php 

}

One response to “Load Google Analytics Tracking Script From Your Functions File”

  1. […] Load Google Analytics Tracking Script From Your Functions File – Both the sample.js file and PHP code to enable you to load your tracking script from your functions file. This way you have total control over both which pages you want tracked and the position the script loads on the page. […]

Was This Tutorial Helpful?