Skip to content

Instantly share code, notes, and snippets.

@kevinlisota
Last active November 1, 2024 15:50
Show Gist options
  • Save kevinlisota/8fd6a90b5e93312413bf to your computer and use it in GitHub Desktop.
Save kevinlisota/8fd6a90b5e93312413bf to your computer and use it in GitHub Desktop.
add WordPress author tracking using Google Analytics custom dimension
//Google Universal Analytics
function google_analytics() { ?>
<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','//www.google-analytics.com/analytics.js','ga');
ga('create', 'YOUR ANALYTICS PROPERTY ID HERE', 'auto');
<?php if (is_singular('post') :
$this_post = get_queried_object();
$author_id = $this_post->post_author;
//dimension index number must be retrieved for your GA property ?>
ga('set', 'dimension1', '<?php echo get_the_author_meta('display_name', $author_id); ?>');
<?php endif; ?>
ga('send', 'pageview');
</script>
<?php }
add_action ('wp_head', 'google_analytics');
@asumm3y
Copy link

asumm3y commented Apr 10, 2015

I'm interested in using this and have added the custom definition / custom dimension
Where would I place this code to have it work?

@kevinlisota
Copy link
Author

This goes in your WordPress theme's functions.php file. Obviously you need to enter your own Google Analytics property ID, and you also need to make sure that the dimension index number matches what you setup in your Google Analytics property.

If your theme already has Google Analytics tracking code, or if you are using some sort of Google Analytics plugin that drops the GA snippet on your page, you'll have to either remove that or customize it. This snippet would add duplicate tracking code in that case, which is not what you want.

Here's an article where I walk through the process of setting this up: http://www.geekwire.com/devblog/add-wordpress-author-tracking-google-analytics-using-custom-dimensions/

@maclonghorn
Copy link

dude, syntax errors abound

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment