Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.