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.
Opens WPIDE on
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
- 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.