0

StackExchange, I am currently creating a website and wish to implement google analytics on it. I am using the new gtag.js and also want to include user id tracking. I've had a little python experience but almost no PHP experience. I have looked through stack overflow and a couple of other places and have come up with this site-specific plugin - is this the most efficient (or even will it work) way of doing it?

<?php
/*
Plugin Name: Analytics Suite
Plugin URI: -redacted-
Description: Implements Google Analytics using the new gtag.js and combining user id.
Author: -redacted-
Version: 1.0
*/
if (is_user_logged_in()) {
 $user = wp_get_current_user();
 $userName = $user->user_login;
}
function ns_google_analytics() { ?>
 <!-- Global site tag (gtag.js) - Google Analytics -->
 <script async src="https://www.googletagmanager.com/gtag/js?id=XXXXXXXXX"></script>
      <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-XXXXXXXX', {
            'user_id': '1'
        });
      </script>
 <?php if (isset($userName)) : ?>
      <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-XXXXXXX', {
            'user_id': '1'
        });
      </script>  
 <?php else : ?>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'XXXXXXXXXXX');
    </script> 
 <?php endif; ?>
 <?php
 }
add_action( 'wp_head', 'ns_google_analytics', 10 );

Thank you in advance, Piklet.

The person who posted below is correct, but I posted as a guest and can't get into that account to mark it as a solution. Thank you so much :)

1

I think you need to do a couple of things:

  • Move your calls to get the user inside your function - PHP variables aren't shared across scopes without using global, which is generally a bad idea because it pollutes the global scope
  • Consolidate your JS
  • Use escaping methods before outputting data

With those in mind, I think this might work for you:

<?php
/**
 * Plugin Name: Analytics Suite
 * Plugin URI: -redacted-
 * Description: Implements Google Analytics using the new gtag.js and combining user id.
 * Author: -redacted-
 * Version: 1.0
 */
function ns_google_analytics() {
    $user = wp_get_current_user();
?>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX"></script>
    <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
<?php if ( 0 !== $user->ID ) : ?>
    gtag('config', 'UA-XXXXXXX', {
        'user_id': '<?php echo esc_js( $user->user_login ); ?>'
    });
<?php else : ?>
    gtag('config', 'UA-XXXXXXX');
<?php endif; ?>
    </script>
 <?php
 }
add_action( 'wp_head', 'ns_google_analytics', 10 );

In the above code:

  • We get the user outright using wp_get_current_user. From the WordPress codex (Emphasis mine):

    WP_User object where it can be retrieved using member variables. Attribute ID will show 0 if there is no user.

  • This means you will always get a \WP_User back, and you can check if the ID is zero to determine if a user is logged in or not.
  • Your conditional if statement really only needs to output specific JS in one spot, so those areas are consolidated
  • All output should be escaped, hence the use of esc_js

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.