Wildcard Redirects for Moved Sections
Redirects whole groups of old URLs with simple * patterns, for example everything under /old-blog/ to the same address under /blog/, without a redirect plugin.
Opens WPIDE on
Code
// Pattern => target. * matches anything; $1, $2 ... insert the matched text. Examples:
// '/old-blog/*' => '/blog/$1',
// '/products/*/manual/' => '/docs/$1/',
$wpide_wildcard_redirects = array();
add_action( 'template_redirect', function () use ( $wpide_wildcard_redirects ) {
$path = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
if ( '' === $path ) {
return;
}
foreach ( $wpide_wildcard_redirects as $pattern => $target ) {
$regex = '#^' . str_replace( '\*', '(.*?)', preg_quote( $pattern, '#' ) ) . '$#i';
if ( ! preg_match( $regex, $path, $matches ) ) {
continue;
}
$url = preg_replace_callback( '/\$(\d+)/', function ( $ref ) use ( $matches ) {
return isset( $matches[ (int) $ref[1] ] ) ? $matches[ (int) $ref[1] ] : '';
}, $target );
$url = preg_match( '#^https?://#i', $url ) ? $url : home_url( $url );
$same_host = ! wp_parse_url( $url, PHP_URL_HOST ) || wp_parse_url( $url, PHP_URL_HOST ) === wp_parse_url( home_url(), PHP_URL_HOST );
if ( $same_host && untrailingslashit( (string) wp_parse_url( $url, PHP_URL_PATH ) ) === untrailingslashit( $path ) ) {
return;
}
wp_safe_redirect( $url, 301 );
exit;
}
}, 1 );
Notes
The rule list is empty by default; add your own using the examples. Use * for any text and $1, $2 in the target for what each * matched. On a subdirectory install include the subdirectory in the patterns. Redirects to the same address are skipped, so a rule cannot loop.
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.