Halloween Sale 15% off Ends in See the plans
PHP

Redirect Old AMP Addresses After Removing AMP

After you stop using an AMP plugin, permanently redirects the old /amp/ and ?amp=1 addresses to the normal pages, so search engines and shared links do not hit errors.

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

Code

add_action( 'template_redirect', function () {
    // Leave everything alone while an AMP plugin is active.
    if ( function_exists( 'amp_is_request' ) || function_exists( 'is_amp_endpoint' ) || defined( 'AMPFORWP_VERSION' ) ) {
        return;
    }

    $uri  = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '';
    $path = (string) wp_parse_url( $uri, PHP_URL_PATH );
    $home = wp_parse_url( home_url() );
    $base = $home['scheme'] . '://' . $home['host'] . ( isset( $home['port'] ) ? ':' . $home['port'] : '' );

    // ?amp=1 or ?amp on any page: drop the parameter.
    if ( isset( $_GET['amp'] ) ) {
        wp_safe_redirect( remove_query_arg( 'amp', $base . $uri ), 301 );
        exit;
    }

    // /my-post/amp/ that no longer exists: go to /my-post/.
    if ( is_404() && preg_match( '#^(.*)/amp/?$#i', $path, $m ) && '' !== $m[1] ) {
        $query = (string) wp_parse_url( $uri, PHP_URL_QUERY );

        wp_safe_redirect( $base . user_trailingslashit( $m[1] ) . ( '' !== $query ? '?' . $query : '' ), 301 );
        exit;
    }
}, 1 );

Notes

Does nothing while an AMP plugin is active.

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.