Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.