Simple Redirect List
Redirects old URLs to new ones with a 301 status from a list you maintain in the snippet. Good for a handful of moved pages.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
// Old path => new path or full URL on this site.
$redirects = array(
'/old-page/' => '/new-page/',
'/2019/promo/' => '/offers/',
);
$request = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '';
$path = '/' . trim( (string) wp_parse_url( $request, PHP_URL_PATH ), '/' ) . '/';
foreach ( $redirects as $from => $to ) {
if ( '/' . trim( $from, '/' ) . '/' !== $path ) {
continue;
}
wp_safe_redirect( preg_match( '#^https?://#', $to ) ? $to : home_url( $to ), 301 );
exit;
}
}, 1 );
Notes
Paths are matched without the query string. On a subdirectory install include the subdirectory in the old path. For other domains, add them with the allowed_redirect_hosts filter.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.