
Redirecting an old WordPress website to a new one is simple as there are many plugins and solutions provided online. However, what I found to be challenging is redirecting only single WordPress posts to another site with or without a plugin.
Redirecting only Posts
To redirect only WordPress posts to a new website then add the code below to your functions.php file in your WordPress child theme.
// Redirect existing posts only
add_action(‘template_redirect’, ‘blogies_post_redirect_only’);
function blogies_post_redirect_only() {
global $post;
if (is_single($post->ID)) {
$new_url = “https://example.com/{$post->post_name}/”;
wp_redirect($new_url, 301);
exit;
}
}
is_single is used to check whether a query is a single post.
$new_url variable is used to redirect to the new URL.
NOTE 1
Replace example.com with your domain name. If you are using a subdomain or subfolder for example “example.com/blog/“, then your new URL should be https://example.com/blog/{$post->post_name}/
NOTE 2
This redirect method only works for published posts. Draft, trash, or deleted posts will not redirect. You will get a 404 error.
If you want to redirect the entire website then add the code below to your htaccess file
# redirect the entire website
RewriteEngine on
RewriteCond %{HTTP_HOST} ^oldmain.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.oldmain.com [NC]
RewriteRule ^(.*)$ https://newdomain.com/$1 [L,R=301,NC]
Replace oldmain.com and newdomain.com with your old and new domain respectively.
Leave a Reply