Last active
November 29, 2024 16:18
-
-
Save swissspidy/7a804f1a65fd0c29df915fc13f7ff1b8 to your computer and use it in GitHub Desktop.
Example sanitizer to add a custom attribute to links in a story
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: Web Stories Link sanitizer example | |
* Description: Example sanitizer to add a custom attribute to links in a story | |
* Author: Pascal Birchler | |
* Author URI: https://pascalbirchler.com/ | |
* Version: 0.0.1 | |
* Requires at least: 6.1 | |
* Requires PHP: 7.4 | |
* License: Apache License 2.0 | |
* License URI: https://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* @copyright 2023 Google LLC | |
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 | |
*/ | |
if ( ! defined( 'ABSPATH' ) ) { | |
exit; | |
} | |
add_action( | |
'init', | |
static function() { | |
if ( ! class_exists( '\Google\Web_Stories_Dependencies\AMP_Base_Sanitizer' ) ) { | |
return; | |
} | |
add_filter( | |
'web_stories_amp_sanitizers', | |
static function( $sanitizers ) { | |
$sanitizers[ Your_Website_Example_AMP_Sanitizer::class ] = []; | |
return $sanitizers; | |
} | |
); | |
class Your_Website_Example_AMP_Sanitizer extends \Google\Web_Stories_Dependencies\AMP_Base_Sanitizer | |
{ | |
/** | |
* Sanitize the HTML contained in the DOMDocument received by the constructor. | |
*/ | |
public function sanitize(): void | |
{ | |
$links = $this->dom->body->getElementsByTagName( 'a' ); | |
/** | |
* The <a> element | |
* | |
* @var DOMElement $link The <a> element | |
*/ | |
foreach ( $links as $link ) { | |
$url = $link->getAttribute( 'href' ); | |
$is_relative_link = str_starts_with( $url, '#' ); | |
if ( ! $is_relative_link && ! $link->getAttribute( 'target' ) ) { | |
$link->setAttribute( 'target', '_blank' ); | |
} | |
$is_link_to_same_origin = str_starts_with( $url, home_url() ) || $is_relative_link; | |
if ( $is_link_to_same_origin ) { | |
$link->setAttribute( 'data-vars-click-url', $url ); | |
} | |
} | |
} | |
} | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment