I’m sure there are tons of plugins for adding Google Analytics to your WordPress site, and a lot of themes have an area for pasting scripts.

But if you ever want to just add the code without any of that, the simplest way is in your functions.php:

add_filter( 'wp_print_footer_scripts', function(){
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'UA-XXXXX-Y', 'auto');
    ga('send', 'pageview');
    <script async src='https://www.google-analytics.com/analytics.js'></script>

This is simply the async code provided by Google.

Of course, that’s not the “right way” to add scripts to your site, although in this case I don’t see a problem.

Here’s a more convoluted but approved way to do it:

add_action( 'wp_enqueue_scripts', function() {

    $id = "UA-XXXXX-Y";

    $code = "window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;

    wp_enqueue_script('google-analytics', 'https://www.google-analytics.com/analytics.js', array(), null, true );

    wp_add_inline_script('google-analytics', $code, 'before' );

add_filter('script_loader_tag', function($tag, $handle) {
    return ( 'google-analytics' === $handle ) ? str_replace( 'src', 'async src', $tag ) : $tag;
}, 10, 2);

Here we’ve enqueued analytics.js with wp_enqueue_script and then added the small snippet with our property ID using the wp_add_inline_script method. The last parameter in both functions refers to the position of the script. “True” puts the script in the footer as opposed to the head, and “before” adds this snippet before the analytics.js link.

The last step is to add the async attribute by hooking in and filtering the script element using script_loader_tag. The filter gets the html <script src='https://www.google-analytics.com/analytics.js'></script>, replaces src with async src and returns it.

Seems a bit overkill, but some useful functions to know.

If you really want to go crazy, you can possibly optimize this code further by replacing




Apparently the official code is written that way simply to prevent issues if the site is a bit hacked and cobbled together and might have 2 GA snippets on the same page (I’ve definitely seen that on some WordPress sites). For discussion, see here and here.

Leave a Reply

Your email address will not be published. Required fields are marked *