Search code examples
wordpresspluginsgoogle-analyticsanalytics

How to add a separate Analytics for each website page in Wordpress


We have a WordPress installation that has locations as separate pages.

For example: mysite.com/colorado and mysite.com/alabama

We need separate google analytics for each of these as well as 1 for all of mysite.com.

Is there a way to do this with a WordPress plugin(s) or will we need to hand code some things?

Thanks in advance!


Solution

  • If I'm not mistaken, Google Analytics lets you view your analytics in a breakdown like that. That said, if you do need individual scripts, it would be relatively easy to program in. There may be some plugins that do this, but I'm not aware of any in particular, though a cursory glance showed plugins like Header and Footer Scripts that allow you to add scripts on a page by page basis.

    Some themes also allow you to add SEO/Script settings per page/post. If that's the case, you can just open up each page and dump each script tag in the "header scripts" or similar section, and call it good. (Genesis is an example of a theme that does this).

    If not, programming this would be relatively straight forward. I'd do it something like this:

    add_action( 'wp_head', 'display_analytics_by_page', 1 );
    function display_analytics_by_page(){
        // Default Script Code with individual UA codes replaced
        $script = '<!-- Global site tag (gtag.js) - Google Analytics -->
            <script async src="https://www.googletagmanager.com/gtag/js?id=[UA-CODE]"></script>
            <script>
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag(\'js\', new Date());
    
              gtag(\'config\', \'[UA-CODE]\');
            </script>';
    
        // Array of UA codes by state
        $codes = array(
            'Alabama' => 'UA-123456789-1',
            'Oregon'  => 'UA-987654542-3',
            'Vermont' => 'UA-000000000-0'
        );
    
        // Get title of this page
        $title = get_the_title();
    
        // If this page title exists in the codes array, swap placeholder and echo it.
        if( isset($codes[$title]) ){
            echo str_replace( '[UA-CODE]', $codes[$title], $script );           
        }
    }
    

    I commented along the way, but the gist is to put in the "default" script, but pull out the UA code. This will only work if you need the same exact script code in each one, otherwise you'll have to add each script to the $codes array instead.

    Then create an array of the UA Codes (or full scripts if needed), keyed by the page title.

    Then check the page title, and if that exists, pull that code in and echo it. This is run on the wp_head hook, so you just need to put this code in your functions.php (or similar) file.