// 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') === 'old-post-permalink') {
// Define the new URL
$new_url = home_url('/new-post-permalink/');
// 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') === 'old-post-permalink' checks if the post slug is 'old-post-permalink'.
- $_SERVER['QUERY_STRING'] to get the query string from the current URL and append it to the new URL.