Back WordPress

Add Google Analytic Code to WordPress Footer With add_action function

WRITTEN BY ON 19 Jul 2011
14,715 VIEWS • SHARES
6 comments

Simple snippet to add script to your WordPress template footer without having to add it into your footer.php. You can use this to append Google Analytic Code by using add_action function and append your script to wp_footer. It's a cleaner solution so your html file always separate from Javascript.

PHP

Open functions.php and append the following. Of course, change $account to your google analytic account.

add_action('wp_footer', 'ga');

function ga() {

	$account = 'UA-1234567-8'; // your account id should look something like this.
	
	$code = "<script type=\"text/javascript\"> 
	 
	  var _gaq = _gaq || [];
	  _gaq.push(['_setAccount', '$account']);
	  _gaq.push(['_trackPageview']);
	 
	  (function() {
	    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	  })();
	 
	</script>"; 
	
	echo $code;

}
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

6 comments
frank 5 years ago
function.php vs footer.php.
Why do you think it's more difficult to edit footer.php and to paste a clean code from googleAnalytics? Stupid way!
Reply
Kevin Liew 5 years ago
this is just a demonstration of how to append code with function.php.
Reply
Adam 5 years ago
If I add this to my functions.php. It completely takes down my site.
Reply
Kevin Liew 5 years ago
updated the code, need to escape the quotes for text/javascript
Reply
Gkfy 5 years ago
would you like to create theme option for these?
regards,
Jenna
Reply
gkfy.com 5 years ago
@frank : no this is not really stupid, if you are facing with wpmu, really useful when you want to put each separate analytics for the child blogs.
Cheers!

Jenna & Andhie
http://gkfy.com
Reply