Custom Sanitizers

The name “sanitizer” is a bit of a misnomer. These are primarily used internally in the plugin to make your site’s content compatible with the amp spec. This involves stripping unsupported tags and attributes and transforming media elements to their matching amp version (e.g. img => amp-img).

Sanitizers are pretty versatile and, unlike Embed Handlers — which work with HTML content as a string — they can be used to manipulate your post’s AMP content using PHP’s DOM library. We’ve included an example that shows you how to use a custom sanitizer to inject ads into your content. You can, of course, do many other things such as add related content.

Step 1: Build the Sanitizer #

Your sanitizer needs to extend the AMP_Base_Sanitizer. In classes/class-ad-inject-sanitizer.php:

class XYZ_AMP_Ad_Injection_Sanitizer extends AMP_Base_Sanitizer {
	public function sanitize() {
		$body = $this->dom->body;

		// Build our amp-ad tag
		$ad_node = AMP_DOM_Utils::create_node( 
			$this->dom, 
			'amp-ad', 
			array(
				// Taken from example at https://github.com/ampproject/amphtml/blob/master/builtins/amp-ad.md
				'width' => 300,
				'height' => 250,
				'type' => 'a9',
				'data-aax_size' => '300x250',
				'data-aax_pubname' => 'test123',
				'data-aax_src' => '302',
			) 
		);

		// Add a placeholder to show while loading
		$fallback_node = AMP_DOM_Utils::create_node( 
			$this->dom, 
			'amp-img', 
			array(
				'placeholder' => '',
				'layout' => 'fill',
				'src' => 'https://placehold.it/300X250',
			) 
		);
		$ad_node->appendChild( $fallback_node );

		// If we have a lot of paragraphs, insert before the 4th one.
		// Otherwise, add it to the end. Note you also have access to
		// XPath via $this->dom->xpath.
		$p_nodes = $body->getElementsByTagName( 'p' );
		if ( $p_nodes->length > 6 ) {
			$p_nodes->item( 4 )->parentNode->insertBefore( $ad_node, $p_nodes->item( 4 ));
		} else {
			$body->appendChild( $ad_node );
		}
	}
}Code language: PHP (php)

Step 2: Load the Sanitizer #

add_filter(
	'amp_content_sanitizers',
	static function ( $sanitizer_classes ) {
		require_once __DIR__ . '/classes/class-ad-inject-sanitizer.php';
		$sanitizer_classes[ XYZ_AMP_Ad_Injection_Sanitizer::class ] = array(
			/*
			 * This array can be used to pass args to your sanitizer and is
			 * accessed within the class via `$this->args`.
			 */
		);
		return $sanitizer_classes;
	}
);Code language: PHP (php)