0

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?

1
  • Your question needs clarifications.. How are those paths created? Child pages? How about assigning those pages to a custom taxonomy, say, Locations and conditionally check using has_term to add the tracking code?
    – Abhik
    May 31, 2021 at 7:44

1 Answer 1

0

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;
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.