Redirect old URLs that now return 404 to their new pages with a simple list, without installing a redirection plugin.
add_action( 'template_redirect', function (): void {
if ( ! is_404() ) {
return;
}
// Old path => new path or full URL.
$redirects = [
'/old-page/' => '/new-page/',
'/2019/05/an-old-post/' => '/blog/an-updated-post/',
'/services/web-design/' => '/services/',
'/old-shop/' => 'https://shop.example.com/',
];
$path = '/' . trim( (string) wp_parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH ), '/' ) . '/';
if ( ! isset( $redirects[ $path ] ) ) {
return;
}
$target = $redirects[ $path ];
wp_redirect( str_starts_with( $target, 'http' ) ? $target : home_url( $target ), 301 );
exit;
} );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
When you rename pages or restructure a site, old links from Google and other sites break. A 301 redirect sends visitors and search engines to the new address and passes the old page’s ranking along.
The snippet only runs when WordPress is about to show a 404, so it never interferes with pages that exist. It normalises the requested path (one leading and one trailing slash, no query string) and looks it up in your list. A match sends a permanent 301 redirect to the new path, or to a full URL on another site.
_wp_old_slug. You only need entries for moves WordPress can’t work out.Visit an old URL from your list. You should land on the new page, and DevTools should show a 301 response.