Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active December 18, 2022 14:22
Show Gist options
  • Save westonruter/f881658cb1bc5a03cc432c8e2b89102a to your computer and use it in GitHub Desktop.
Save westonruter/f881658cb1bc5a03cc432c8e2b89102a to your computer and use it in GitHub Desktop.
<?php
/**
* AMP Path Prefix Paired URLs plugin file.
*
* @package Google\AMP_Path_Prefix_Paired_URLs
* @author Weston Ruter, Google
* @license GPL-2.0-or-later
* @copyright 2020 Google Inc.
*
* @wordpress-plugin
* Plugin Name: AMP Path Prefix Paired URLs
* Plugin URI: https://gist.github.com/westonruter/f881658cb1bc5a03cc432c8e2b89102a
* Description: Demonstration of how to configure AMP plugin v2.1 to use an "amp" path prefix for paired AMP URLs (in Transitional mode or Reader mode). Depends on <a href="https://github.com/ampproject/amp-wp/pull/5558">amp-wp#5558</a>.
* Version: 0.3
* Author: Weston Ruter, Google
* 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/f881658cb1bc5a03cc432c8e2b89102a
*/
namespace AMP_Path_Prefix_Paired_URLs;
add_filter(
'amp_custom_paired_url_structure',
function () {
require_once __DIR__ . '/PrefixUrlStructure.php';
return PrefixUrlStructure::class;
}
);
<?php
/**
* Class PrefixUrlStructure.
*
* @package Google\AMP_Path_Prefix_Paired_URLs
*/
namespace AMP_Path_Prefix_Paired_URLs;
use AmpProject\AmpWP\PairedUrlStructure;
/**
* Descriptor for paired URL structures that start in /amp/ path prefix.
*/
class PrefixUrlStructure extends PairedUrlStructure {
/**
* Add amp subdomain to a URL.
*
* @param string $url URL (or REQUEST_URI).
* @return string URL with AMP path prefix.
*/
public function add_endpoint( $url ) {
if ( $this->has_endpoint( $url ) ) {
return $url;
}
$slug = amp_get_slug();
return preg_replace(
'#^((\w+:)?//[^/]+)?/#',
"$1/{$slug}/",
$url
);
}
/**
* Remove AMP path prefix from a URL.
*
* @param string $url URL (or REQUEST_URI).
* @return string URL without AMP path prefix.
*/
public function remove_endpoint( $url ) {
return preg_replace(
sprintf(
'#^((\w+:)?//[^/]+)?/%s/#',
preg_quote( amp_get_slug(), '#' )
),
'$1/',
$url
);
}
}
@westonruter
Copy link
Author

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