Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active June 2, 2020 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westonruter/1eeb2224004c0e904fa2a35fc92899c0 to your computer and use it in GitHub Desktop.
Save westonruter/1eeb2224004c0e904fa2a35fc92899c0 to your computer and use it in GitHub Desktop.
<?php
/**
* Convert amp-anim to amp-img
*
* @package AMP_Anim_To_AMP_Img
* @author Weston Ruter, Google
* @license GPL-2.0-or-later
* @copyright 2019 Google Inc.
*
* @wordpress-plugin
* Plugin Name: Convert amp-anim to amp-img
* Description: Force animated GIFs to be rendered in <code>amp-img</code> instead of <code>amp-anim</code> after the image sanitizer has processed the underlying <code>img</code> tags. See <a href="https://github.com/ampproject/amphtml/issues/24306#issuecomment-527688934">amphtml#24306</a>.
* Plugin URI: https://gist.github.com/westonruter/1eeb2224004c0e904fa2a35fc92899c0
* Version: 0.1.0
* 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/1eeb2224004c0e904fa2a35fc92899c0
*/
namespace AMP_Anim_To_AMP_Img;
/**
* Define sanitizer and register it.
*/
function init() {
/**
* Class Sanitizer
*/
class Sanitizer extends \AMP_Base_Sanitizer {
/**
* Convert.
*/
public function sanitize() {
/**
* Elements.
*
* @var \DOMElement[] $amp_anims
*/
// Convert live node list to array.
$amp_anims = [];
foreach ( $this->dom->getElementsByTagName( 'amp-anim' ) as $amp_anim ) {
$amp_anims[] = $amp_anim;
}
// Now replace them.
foreach ( $amp_anims as $amp_anim ) {
$amp_img = $this->dom->createElement( 'amp-img' );
foreach ( $amp_anim->attributes as $attribute ) {
$amp_img->setAttribute( $attribute->nodeName, $attribute->nodeValue );
while ( $amp_anim->firstChild ) {
$amp_img->appendChild( $amp_anim->firstChild );
}
}
$amp_anim->parentNode->replaceChild( $amp_img, $amp_anim );
}
}
} // End class Sanitizer.
// Inject the new sanitizer right after the image sanitizer.
add_filter(
'amp_content_sanitizers',
function( $old_sanitizers ) {
$new_sanitizers = [];
foreach ( $old_sanitizers as $sanitizer_class => $sanitizer_args ) {
$new_sanitizers[ $sanitizer_class ] = $sanitizer_args;
if ( 'AMP_Img_Sanitizer' === $sanitizer_class ) {
$new_sanitizers[ __NAMESPACE__ . '\Sanitizer' ] = $sanitizer_args;
}
}
return $new_sanitizers;
}
);
}
add_action( 'amp_init', __NAMESPACE__ . '\init' );
@westonruter
Copy link
Author

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