WordPress post slug redirection

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.