Adding Google Analytics to footer selectively

    // add google analytics to footer
function add_google_analytics() { ?>
    if ( !is_user_logged_in() ) {

    <!--Google Analytics-->
    <script type="text/javascript">
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
      _gaq.push(['_trackPageview']);
      _gaq.push(['_trackPageLoadTime']);

      (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>
}
<?php }

add_action('wp_footer', 'add_google_analytics');

Trying to create a function that adds google analytics tracking code depending on whether or not the user is logged into WordPress. Right now, the tracking code is added all the time.

Related posts

Leave a Reply

1 comment

  1. You have the ?> and ?php at wrong place, this way user logged in testing is a simple text.
    Try this:

    // add google analytics to footer
    function add_google_analytics() {
        if ( !is_user_logged_in() ) 
        {
        ?>
            <!--Google Analytics-->
            <script type="text/javascript">
                var _gaq = _gaq || [];
                _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
                _gaq.push(['_trackPageview']);
                _gaq.push(['_trackPageLoadTime']);
                (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>
        <?php
        }
    }
    
    add_action('wp_footer', 'add_google_analytics');