1
    // 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.

  • do you have any kind of caching going on in your site? – Bainternet Jul 1 '11 at 6:36
  • Do you want the code to appear if they are logged in or if they aren't logged in? – supajb Jul 1 '11 at 7:38
2

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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.