Skip to content

Instantly share code, notes, and snippets.

@felixarntz
Created August 12, 2019 09:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felixarntz/01f7099ec718d73fb25ff81fc408111b to your computer and use it in GitHub Desktop.
Save felixarntz/01f7099ec718d73fb25ff81fc408111b to your computer and use it in GitHub Desktop.
WordPress mini plugin for AMP that transforms all images linking to themselves to open in an `amp-image-lightbox` overlaying the website content. For docs on the component, see https://amp.dev/documentation/components/amp-image-lightbox/
<?php
/**
* Class: AMP_Image_Lightbox_Links\\Sanitizer
*
* @package AMP_Image_Lightbox_Links
* @author Felix Arntz, Google
* @license GPL-2.0-or-later
* @copyright 2019 Google Inc.
*/
namespace AMP_Image_Lightbox_Links;
use AMP_Base_Sanitizer;
use DOMXPath;
/**
* Class sanitizing images linking to themselves to use the amp-image-lightbox component.
*/
class Sanitizer extends AMP_Base_Sanitizer {
/**
* XPath for the DOMDocument.
*
* @var DOMXPath
*/
protected $xpath;
/**
* Sanitizes the HTML contained in the DOMDocument.
*/
public function sanitize() {
$this->xpath = new DOMXPath( $this->dom );
$this->add_image_lightbox();
}
/**
* Replaces image links to themselves with the amp-image-lightbox component.
*/
protected function add_image_lightbox() {
$linked_images = $this->xpath->query( '//a[@href]/child::amp-img' );
if ( ! $linked_images->length ) {
return;
}
$count = 0;
foreach ( $linked_images as $linked_image ) {
$link = $linked_image->parentNode;
$href = preg_replace( '/-(\d+)x(\d+)\.(jpg|png|gif)$/', '.$3', $link->getAttribute( 'href' ) );
$src = preg_replace( '/-(\d+)x(\d+)\.(jpg|png|gif)$/', '.$3', $linked_image->getAttribute( 'src' ) );
if ( $href !== $src ) {
continue;
}
$linked_image->setAttribute( 'on', 'tap:linked-image-lightbox.open' );
$linked_image->setAttribute( 'role', 'button' );
$linked_image->setAttribute( 'tabindex', '0' );
$link->parentNode->replaceChild( $linked_image, $link );
$count++;
}
if ( ! $count ) {
return;
}
$lightbox = $this->dom->createElement( 'amp-image-lightbox' );
$lightbox->setAttribute( 'id', 'linked-image-lightbox' );
$lightbox->setAttribute( 'layout', 'nodisplay' );
$lightbox->setAttribute( 'data-close-button-aria-label', _x( 'Close', 'lightbox', 'amp-image-lightbox-links' ) );
$this->dom->getElementsByTagName( 'body' )->item( 0 )->appendChild( $lightbox );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment