AMP Fallback Image

AMP requires an image for each post, so if you don’t specify a featured image you’ll get the following error in the Structured Data Testing Tool:

The code below adds a fallback image to the AMP plugin. The actual fallback image ID is ct_get_option( 'default_post_image_id' ) because I’m using a CMB2 Options page to make the default image editable by the client. Alternatively you could replace that with a hardcoded image ID.

<?php
/**
* AMP Fallback Image
* If no image is specified, use a site-wide default.
*
*/
function ea_amp_fallback_image( $data ) {
if( ! isset( $data['metadata']['image'] ) || empty( $data['metadata']['image'] ) ) {
$image = wp_get_attachment_image_src( ct_get_option( 'default_post_image_id' ), 'full' );
if( $image && ! is_wp_error( $image ) && is_array( $image ) ) {
$data['metadata']['image'] = array(
'@type' => 'ImageObject',
'url' => $image[0],
'width' => $image[1],
'height' => $image[2],
);
}
}
return $data;
}
add_filter( 'amp_post_template_data', 'ea_amp_fallback_image' );
view raw functions.php hosted with ❤ by GitHub

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk