Google Analytics Plugin with UserId tracking

Hi,

I’m trying to implement GA analytics with UserId tracking. This requires extra code, and must execute PHP inside the script tag.

The code should be something like:

<?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>

Will this work in the GA plugin? If I simply copy paste this? Or do I need to use child theme? In which case, do I edit functions.php?

Hi there,

You will need to use the Child Theme functions.php. Kindly use the wp_head hook for that. You can find a good example in the article below:

https://theme.co/apex/forum/t/customizations-actions-and-filters-in-x/208

Thank you.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.