Embed Handlers are helper classes to inject AMP-specific content for your oEmbeds and shortcodes.
Embed Handlers register the embeds they handle using standard WordPress functions such as add_shortcode
. For working examples, check out the existing implementations for Instagram, Twitter, etc. as guides to build your own.
While the primary purpose of Embed Handlers is for use with embeds, you can use them for adding AMP-specific the_content
callbacks as well.
Build the Embed Handler #
Your Embed Handler class needs to extend the AMP_Base_Embed_Handler
class.
Note: make sure to set proper priorities or remove existing callbacks for your regular content.
In classes/class-amp-related-posts-embed.php
:
class XYZ_AMP_Related_Posts_Embed extends AMP_Base_Embed_Handler {
public function register_embed() {
// If we have an existing callback we are overriding, remove it.
remove_filter( 'the_content', 'xyz_add_related_posts' );
// Add our new callback
add_filter( 'the_content', array( $this, 'add_related_posts' ) );
}
public function unregister_embed() {
// Let's clean up after ourselves, just in case.
add_filter( 'the_content', 'xyz_add_related_posts' );
remove_filter( 'the_content', array( $this, 'add_related_posts' ) );
}
public function get_scripts() {
return array(
'amp-mustache' => 'https://cdn.ampproject.org/v0/amp-mustache-0.1.js',
'amp-list' => 'https://cdn.ampproject.org/v0/amp-list-0.1.js',
);
}
public function add_related_posts( $content ) {
// See https://github.com/ampproject/amphtml/blob/master/extensions/amp-list/amp-list.md for details on amp-list
$related_posts_list = '
<amp-list src="https://data.com/articles.json?ref=CANONICAL_URL" width=300 height=200 layout=responsive>
<template type="amp-mustache">
<div>
<amp-img src="{{imageUrl}}" width=50 height=50></amp-img>
{{title}}
</div>
</template>
<div overflow role=button class="list-overflow">
Show more
</div>
</amp-list>';
$content .= $related_posts_list;
return $content;
}
}
Code language: PHP (php)
Step 2: Load the Embed Handler #
add_filter( 'amp_content_embed_handlers', 'xyz_amp_add_related_embed', 10, 2 );
function xyz_amp_add_related_embed( $embed_handler_classes, $post ) {
require_once( dirname( __FILE__ ) . '/classes/class-amp-related-posts-embed.php' );
$embed_handler_classes[ 'XYZ_AMP_Related_Posts_Embed' ] = array();
return $embed_handler_classes;
}
Code language: PHP (php)