Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active April 2, 2022 17:18
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 westonruter/9610b49e3138ec95a000590dddd13044 to your computer and use it in GitHub Desktop.
Save westonruter/9610b49e3138ec95a000590dddd13044 to your computer and use it in GitHub Desktop.
<?php
/**
* AMP FX Blocks plugin bootstrap.
*
* @package Google\AMP_FX_Blocks
* @author Weston Ruter, Google
* @license GPL-2.0-or-later
* @copyright 2021 Google Inc.
*
* @wordpress-plugin
* Plugin Name: AMP FX Blocks
* Plugin URI: https://gist.github.com/westonruter/9610b49e3138ec95a000590dddd13044
* Description: Inject <a href="https://amp.dev/documentation/components/amp-fx-collection/">AMP visual effects</a> into blocks via class names, for example <code>amp-fx=parallax data-parallax-factor=1.5</code>. For multiple effects, separate with a comma for example <code>amp-fx=fade-in,fly-in-right</code>.
* Version: 0.2.2
* 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/9610b49e3138ec95a000590dddd13044
*/
namespace Google\AMP_FX_Blocks;
add_filter(
'render_block',
static function ( $block_content, $block ) {
if (
empty( $block['attrs']['className'] )
||
! function_exists( 'is_amp_endpoint' )
||
! is_amp_endpoint()
) {
return $block_content;
}
$fx_names = [];
$data_attrs = [];
$classes = preg_split( '/\s+/', trim( $block['attrs']['className'] ) );
foreach ( $classes as $class ) {
$parts = explode( '=', $class, 2 );
if ( 2 !== count( $parts ) ) {
continue;
}
list( $key, $value ) = $parts;
if ( ! isset( $value ) ) {
continue;
}
if ( 'amp-fx' === $key ) {
$fx_names = explode( ',', $value );
} elseif ( false !== strpos( $key, 'data-' ) ) {
$data_attrs[ sanitize_key( $key ) ] = $value;
}
}
if ( empty( $fx_names ) ) {
return $block_content;
}
$attrs = [ sprintf( 'amp-fx="%s"', esc_attr( implode( ' ', $fx_names ) ) ) ];
foreach ( $data_attrs as $key => $value ) {
$attrs[] = sprintf( '%s="%s"', esc_attr( $key ), esc_attr( $value ) );
}
$block_content = preg_replace(
'/^\s*<\w+(?=\s|>)/',
'$0 ' . implode( ' ', $attrs ),
$block_content,
1
);
return $block_content;
},
10,
2
);
@westonruter
Copy link
Author

@westonruter
Copy link
Author

westonruter commented Mar 5, 2021

Example usage:

👉 Important note: Do not include the quotation marks around the attribute values.

To supply multiple effects, separate by comma: amp-fx=fade-in,fly-in-right.

image

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