1

I am maintaining a website and noticed an odd behavior on page redirection, the website is indexed in Google, and posts are listed on Google Search Results, but it looks like the post slugs could be cached and are listed differently on Google Search results and in Wordpress, for example:

On Google Search results the post is listed as: https://mywebsite.com/news-from-new-york-2

and on Wordpress it is listed as: https://mywebsite.com/news-from-new-york

When the first URL is opened Wordpress redirects to the second one, which is fine but for UTM campaigns the UTM params are lost on the redirection, any help on how I could setup this redirection to keep the UTM params?

2 Answers 2

2

You can use the next PHP code:

// NAV: Custom Redirect
function wpcoder_custom_redirect() {
    // Check if the current URL is the one you want to redirect
    if (is_single() && is_main_query() && get_post_field('post_name') === 'news-from-new-york') {
        // Define the new URL
        $new_url = home_url('/news-from-new-york-2/');

        // Get the query string from the current URL
        $query_string = $_SERVER['QUERY_STRING'];


        // Append the query string to the new URL
        if ($query_string) {
            $new_url .= '?' . $query_string;
        }

        // Perform the redirect
        wp_redirect($new_url, 301); // Use 301 for permanent redirect, or 302 for temporary redirect
        exit();
    }
}

// Hook the custom redirect function to the 'template_redirect' action
add_action('template_redirect', 'wpcoder_custom_redirect');

In this code:

  • The is_single() function checks if the current page is a single post.
  • The is_main_query() function ensures that it's the main query on the page.
  • get_post_field('post_name') === 'news-from-new-york' checks if the post slug is 'news-from-new-york'.
  • $_SERVER['QUERY_STRING'] to get the query string from the current URL and append it to the new URL.

If these conditions are met, the function redirects the user to the new URL. Adjust the conditions based on your specific requirements.

You can add this code to the functions.php file or use the free WP Coder plugin through the Global PHP page.

1
  • Please do no copy/paste ChatGPT answers
    – AugustoM
    Commented Dec 11, 2023 at 7:43
1

After trying a few ideas this is what really solved this issue:

  1. First the utm should be captured before the redirection happens and thus the 'wp' hook should be used.
  2. To persists the captured utms, those are stored in a session variable
  3. When the post is called in single.php file, pull the session variable

in functions.php

function capture_utm () {
    if (!session_id()) {
        session_start();        
    }

    if (is_single()) {
        $requested_url = $_SERVER['REQUEST_URI'];

        if (strpos($requested_url, 'utm_') !== false) {
            parse_str($_SERVER['QUERY_STRING'], $query_params);
            $utm_params = array_filter($query_params, function ($key) {
                return strpos($key, 'utm_') === 0;
            }, ARRAY_FILTER_USE_KEY);
            $_SESSION['utm_params'] = $utm_params;
        }
    }
}
add_action('wp', 'capture_utm');

Then in single.php file:

<?php
    if (isset($_SESSION['utm_params']) && !empty($_SESSION['utm_params'])) {
        $utm_query = json_encode($_SESSION['utm_params']);
        ?>
        <script>
            document.addEventListener('DOMContentLoaded', function(){
                let currentURL = window.location.href;
                let utmParameters = <?php echo $utm_query; ?>

                if (Object.keys(utmParameters).length > 0) {
                    utmQueryString = Object.entries(utmParameters)
                    .map(function (entry) {
                        return entry.join('=');
                    })
                    .join('&');

                    let newURL = currentURL + (currentURL.includes('?') ? '&' : '?') + utmQueryString;

                    window.history.replaceState({}, document.title, newURL);
                }
            }, false);
        </script>
        <?php
        unset($_SESSION['utm_params']);
    }

This pass the utms to the page and any click on it is captured by Google GTM. Single PHP file should start a session somewhere though with session_start().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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