• Hi,

    I know that there are plugins to add google analytics, but I want to do it myself, using functions.php.

    I came up with this:

    // Add google analytics tracking code to non-logged-in users
    function google_analytics() {
           wp_register_script( 'google-analytics', get_stylesheet_directory_uri().'/scripts/ga.js', '', '', false );
          wp_enqueue_script( 'google-analytics' );
         }
        if (!is_user_logged_in()) {
         add_action( 'wp_enqueue_scripts', 'google_analytics' );
    }

    Now it all looks like it should work. When I go to any page (while not logged-in) I can view page source and see this in the header:
    <script type='text/javascript' src='https://oldmankit.com/wp-content/themes/omkv2/scripts/ga.js?ver=3.5.1'></script>

    However, it doesn’t seem to actually ‘kick in’. I can go to google analytics real-time mode and I cannot see myself viewing the page.

    I have a much less tidy option which works (I show-up in real-time mode on google analytics):

    function add_googleanalytics() {
    if (!is_user_logged_in()) { ?>
    	<script type="text/javascript">
    	  var _gaq = _gaq || [];
      	_gaq.push(['_setAccount', 'UA-37314571-1']);
      	_gaq.push(['_setDomainName', 'oldmankit.com']);
      	_gaq.push(['_trackPageview']);
      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'https://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    	  })();
    	</script>
    <?php }
    }
    
    add_action('wp_footer', 'add_googleanalytics');

    But I don’t really want to have javascript in functions.php.

    Can anyone tell me what I’ve done wrong with the first option?

  • The topic ‘Correct way to add google analytics script’ is closed to new replies.