The Genesis theme framework includes a useful function for retrieving a post image: genesis_get_image()
. It uses the featured image, but if no featured image is specified it will use the first image uploaded to the post.
Yoast SEO only looks at the featured image for a post. If there is no featured image, no image is attached to the article’s schema and you’ll get a schema error (screenshot).
The following code will only run on singular content (posts, pages…) that do not have a featured image. It sees if genesis_get_image()
can find an image in the post, and if so it sets that as the image in Yoast SEO’s schema.
<?php
/**
* Use Genesis Image in Yoast Schema
* If no featured image is specified, genesis_get_image() uses first uploaded to post
*
* @link https://www.billerickson.net/code/yoast-schema-use-genesis-image/
*/
function be_yoast_schema_use_genesis_image( $graph_piece ) {
if( ! is_singular() )
return $graph_piece;
if( empty( $graph_piece['image'] ) && function_exists( 'genesis_get_image' ) ) {
$image = genesis_get_image( array( 'format' => 'url' ) );
if( !empty( $image ) )
$graph_piece['image'] = array(
'@id' => $image . '#primaryimage',
'@type' => 'ImageObject',
'url' => $image,
);
}
return $graph_piece;
};
add_filter( 'wpseo_schema_article', 'be_yoast_schema_use_genesis_image' );