Multiple Google Analytics for Multiple pagepath

I have a landing page with one domain with multiple page path depending on my clients location,

Now, I have already setup different GA tracking code and I want to track this way

GA Property Code 1 = www.example.com/page/path1, www.example.com/page/path2, www.example.com/page/path3 etc

GA Property Code 2 = www.example.com/page/path10, www.example.com/page/path15, www.example.com/page/path16 etc

How do I go about this?

Topic google-analytics Wordpress

Category Web


You hook into the wp_footer and add your GA code.

Here's is how I would do it.

Option 1:

Get the current URL and counter check it with you selected URLs.

add_action('wp_footer', 'wpse388915_custom_ga_code', 99);
function wpse388915_custom_ga_code() {

    $current_url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    
    switch($current_url) {
        case 'www.example.com/page/path1': 
        case 'www.example.com/page/path2': 
        case 'www.example.com/page/path3': 
            echo 'GA Property Code 1';
            break;
        
        case 'www.example.com/page/path10': 
        case 'www.example.com/page/path15': 
        case 'www.example.com/page/path16': 
            echo 'GA Property Code 2';
            break;
    }
}

Option 2:

Get the current URL, then fetch the post ID from the URL using url_to_postid and counter check it with you selected post/page IDs.

add_action('wp_footer', 'wpse388915_custom_ga_code', 99);
function wpse388915_custom_ga_code() {

    $current_url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    
    $post_id = url_to_postid($current_url);
    
    // Return if page does not exist.
    if (!$post_id) return;
    
    $preferred_post_type = get_post_field('post_type', $post_id);
    
    if ($preferred_post_type == 'my_post_type') {
        switch($post_id) {
            case 1: 
            case 2: 
            case 3: 
                echo 'GA Property Code 1';
                break;
            
            case 10: 
            case 15: 
            case 16: 
                echo 'GA Property Code 2';
                break;
        }
    }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.