Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* AMP Rewrite Endpoint Removal plugin.
*
* @author Weston Ruter, Google
* @license GPL-2.0-or-later
* @copyright 2019 Google Inc.
*
* @package AMP_Rewrite_Endpoint_Removal
*
* Plugin Name: AMP Rewrite Endpoint Removal
* Description: Automatically redirect URLs with the /amp/ endpoint or the ?amp query var to the URL without. This is only useful when removing the AMP plugin. The plugin does nothing if the AMP plugin is active. Flush your permalinks if you experience problems.
* Version: 0.1
* Plugin URI: https://gist.github.com/westonruter/b7eb9cc7648b9a8b94b0015c79c8702e
* Author Name: Weston Ruter
* Author URI: https://weston.ruter.net/
* License: GNU General Public License v2 (or later)
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
* Gist Plugin URI: https://gist.github.com/westonruter/b7eb9cc7648b9a8b94b0015c79c8702e
*/
namespace AMP_Rewrite_Endpoint_Removal;
const SLUG = 'amp';
function init() {
if ( function_exists( 'amp_init' ) ) {
return;
}
add_amp_endpoint();
add_action( 'template_redirect', __NAMESPACE__ . '\redirect_non_amp' );
}
function add_amp_endpoint() {
add_rewrite_endpoint( SLUG, \EP_PERMALINK );
}
register_activation_hook( __FILE__, __NAMESPACE__ . '\flush_rewrite_rules' );
add_action( 'init', __NAMESPACE__ . '\init' );
function flush_rewrite_rules() {
add_amp_endpoint();
\flush_rewrite_rules( false );
}
function redirect_non_amp() {
if ( false === get_query_var( SLUG, false ) && ! isset( $_GET[ SLUG ] ) ) {
return;
}
$original_url = wp_unslash( $_SERVER['REQUEST_URI'] );
$url = $original_url;
// Strip endpoint.
$url = preg_replace( ':/' . preg_quote( SLUG, ':' ) . '(?=/?(\?|#|$)):', '', $url );
// Strip query var.
$url = remove_query_arg( SLUG, $url );
if ( $url !== $original_url ) {
wp_safe_redirect( $url, 301 );
exit;
}
}
@westonruter

This comment has been minimized.

Copy link
Owner Author

@westonruter westonruter commented Apr 4, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment