The right way to redirect post after deleted, redirect deleted post or page to homepage or to another post, easy way and simple.
How to Redirect Post after Deleted
Using wp_redirect() function and template_redirect action, and is_404() function, we will redirect deleted posts or pages (in the Trash or Permanently deleted).
Redirect Post Function
Copy function code and paste it in your functions.php file:
function WPTime_redirect_deleted_posts(){ if( is_404() ){ $get_slug = rtrim($_SERVER['REQUEST_URI'], '/'); $deleted_slug = rtrim('/about/', '/'); if( $get_slug == $deleted_slug ){ wp_redirect( home_url('/'), 301 ); // Redirect about page to homepage exit(); } } } add_action('template_redirect', 'WPTime_redirect_deleted_posts');
Now if “about” page (or post) is deleted, will be redirect “about” page to homepage.
Note: If your WordPress blog inside “Directory”, for example if your website link like this:
http://example.com/blog/
You must to change this:
$deleted_slug = rtrim('/about/', '/');
To this:
$deleted_slug = rtrim('/blog/about/', '/');
If you want to redirect deleted post or page to another post or page, change this:
wp_redirect( home_url('/'), 301 );
To this:
wp_redirect( home_url('/some-post/'), 301 ); // Use '/blog/some-post/' if your blog inside Directory.
Redirect Multi Deleted Posts
This an example to redirect multi deleted posts or pages:
function WPTime_redirect_multi_deleted_posts(){ if( is_404() ){ $get_slug = rtrim($_SERVER['REQUEST_URI'], '/'); if( $get_slug == rtrim('/deleted-post-number-1/', '/') ){ wp_redirect( home_url('/contact-page/'), 301 ); // Redirect http://example.com/deleted-post-number-1/ To contact page. exit(); } if( $get_slug == rtrim('/deleted-post-number-2/', '/') ){ wp_redirect( home_url('/'), 301 ); exit(); } if( $get_slug == rtrim('/deleted-post-number-3/', '/') ){ wp_redirect( home_url('/some-post/'), 301 ); exit(); } } } add_action('template_redirect', 'WPTime_redirect_multi_deleted_posts');