SEO PHP Intermediate

Add 301 Redirects Without a Plugin

Redirect old URLs that now return 404 to their new pages with a simple list, without installing a redirection plugin.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 22 lines
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;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • Keep the list short; a few dozen entries is fine. For hundreds of redirects, use your server, your CDN or a redirection plugin with its own table.
  • WordPress already redirects posts whose slug you changed, using _wp_old_slug. You only need entries for moves WordPress can’t work out.
  • Paths are matched exactly, including case.

How to test it

Visit an old URL from your list. You should land on the new page, and DevTools should show a 301 response.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only