Created
November 29, 2024 16:23
-
-
Save swissspidy/a86f1eabefd24827646973ec4f497539 to your computer and use it in GitHub Desktop.
Web Stories link utm_source sanitizer example
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 add "?utm_source=page_xx" to all links in a story. | |
* Author: Pascal Birchler | |
* Author URI: https://pascalbirchler.com/ | |
* Version: 0.0.1 | |
* Requires at least: 6.4 | |
* 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 { | |
$page_nubmer = 0; | |
$pages = $this->dom->body->getElementsByTagName( 'amp-story-page' ); | |
/** | |
* The <amp-story-page> element | |
* | |
* @var DOMElement $page The <a> element | |
*/ | |
foreach ( $pages as $page ) { | |
$page_nubmer++; | |
$links = $page->getElementsByTagName( 'a' ); | |
/** | |
* The <a> element | |
* | |
* @var DOMElement $link The <a> element | |
*/ | |
foreach ( $links as $link ) { | |
$url = $link->getAttribute( 'href' ); | |
$url = add_query_arg( | |
[ | |
'utm_source' => | |
"page_$page_nubmer" | |
], | |
$url | |
); | |
$link->setAttribute( 'href', $url ); | |
} | |
} | |
} | |
} | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment