$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>plugins - WordPress gtag.js with User ID tracking|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

plugins - WordPress gtag.js with User ID tracking

matteradmin8PV0评论

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=""></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 :)

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/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 :)

Share Improve this question edited Feb 6, 2019 at 9:12 Piklet 71 bronze badge asked Feb 5, 2019 at 12:57 PikletPiklet 1
Add a comment  | 

1 Answer 1

Reset to default 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/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
Post a comment

comment list (0)

  1. No comments so far