Last active
June 2, 2020 06:07
-
-
Save westonruter/7358d6669e09cfa15a99021204208a67 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Installation instructions: https://gist.github.com/westonruter/6110fbc4bef0c4b8c021a112012f7e9c