Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westonruter/7358d6669e09cfa15a99021204208a67 to your computer and use it in GitHub Desktop.
Save westonruter/7358d6669e09cfa15a99021204208a67 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: AMP Schema.org Meta Image Content Fallback
* Description: Promote content image as Schema.org image when no featured image is supplied.
* Plugin URI: https://gist.github.com/westonruter/7358d6669e09cfa15a99021204208a67
* Author: Weston Ruter
* Author URI: https://weston.ruter.net/
* Gist Plugin URI: https://gist.github.com/westonruter/7358d6669e09cfa15a99021204208a67
*/
add_filter(
'amp_schemaorg_metadata',
function( $data ) {
if ( ! is_singular() || ! empty( $data['image'] ) || ! get_post() ) {
return $data;
}
if ( preg_match_all( '#<img\s[^>]+(?:\s|"|\')wp-image-(\d+)(?:\s|"|\')[^>]*>#s', get_post()->post_content, $matches ) ) {
$attachment_ids = $matches[1];
foreach ( $attachment_ids as $attachment_id ) {
$src = wp_get_attachment_image_src( $attachment_id, 'full' );
if ( ! $src ) {
continue;
}
list( $url, $width ) = $src;
if ( $width > 1200 ) {
$data['image'] = array(
'@type' => 'ImageObject',
'url' => $url,
);
break;
}
}
} elseif ( preg_match( '#<img\s[^>]*src=(?:"|\')(.+?)(?:"|\')#s', get_post()->post_content, $matches ) ) {
$data['image'] = array(
'@type' => 'ImageObject',
'url' => $matches[1],
);
}
return $data;
},
100
);
@westonruter
Copy link
Author

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