Use Google Analytics’ User ID function with WordPress site

Searching the web high and low for an answer!

I need to integrate Google analytics’ ‘user ID’ function with my wordpress site.
See: https://support.google.com/analytics/answer/3123662?hl=en

Read More

Been looking for a dedicated plugin but closest thing I could find was https://en-gb.wordpress.org/plugins/google-analytics-adder/ but the lack of instructions left me without a solution.

Currently have GA installed and running fine currently with Yoast’s plugin, but not this user ID function. So I can’t identify registered users interactions.

I do understand that WP generates an ID for each user, my question is more regarding how to send this to GA (and if sending WP’s user ID is best practice?)

Not sure if wordpress is natively/easily able to “send the unique IDs generated by your own authentication system to Analytics as values for the User ID”.

Any help appreciated!

Related posts

2 comments

  1. Use this. Mind that it will only work for logged-in users, not sure if this is what you want to achieve:

    ga('set', 'userId', <?php echo get_current_user_id(); ?>);
    
  2. You can use the _setCustomVar method from the JavaScript API to provide the user name of the current user. To my knowledge no GA plugins for WordPress support this, so you will need to put your tracking code directly into the theme or write a custom plugin for it. The custom variable will then show up as a segment in Google Analytics. To get the current user you can use the wp_get_current_user API call.

    For the Universal Analytics version:

    <?php
        if (is_user_logged_in()) {
            $user = wp_get_current_user();
            $userName = $user->user_login;
        }
    ?>
    <script>
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
    
        ga('create', 'UA-XXXX-1', 'auto');
        <?php if (isset($userName)) : ?>
            ga('set', 'userId', <?php echo(json_encode($userName)); ?>); // Set the user ID using signed-in user_id.
        <?php endif; ?>
        ga('send', 'pageview');
    </script>
    

    Cross Posted from : 16578410

Comments are closed.