Adding Google Analytics Tracking Script in WordPress Admin

How to add Google Analytics tracker in WordPress admin? It’s easy. You just need to add a few lines in your theme functions.php. This is the WordPress admin_head hook.


add_action('admin_head', 'add_google_analytics');

This is the add_google_analytics function.


function add_google_analytics(){

if(!current_user_can('level_10')):

echo "<script type='text/javascript'>

var _gaq = _gaq || [];
window.google_analytics_uacct = 'UA-XXXXXXXX-XX';
_gaq.push(['_setAccount', 'UA-XXXXXXXX-XX']);
_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>";

endif;

}

Change UA-XXXXXXXX-XX from your Google Analytics tracking script.Oh, what is it if(!current_user_can(‘level_10’)): ? It’s a bonus for you because I think you don’t need yourself to be tracked by your analytics. So, it only tracks those who logged in not as admin.

Remember DO NOT copy paste your analytics tracking script directly. You must change the double quote (“) to single quote (‘) or you’ll get error and it will make you busy because you have to fix it through cPanel if you’re self hosted.

Leave a Reply