Skip to content

Instantly share code, notes, and snippets.

@cabrailsford
Created July 14, 2020 17:29
Show Gist options
  • Save cabrailsford/4e86f120b695d03df2dc7b33f99b35e4 to your computer and use it in GitHub Desktop.
Save cabrailsford/4e86f120b695d03df2dc7b33f99b35e4 to your computer and use it in GitHub Desktop.
Function to get YoastSEO Open Graph image from postmeta, falling back to post_thumbnail if it exists.
<?php
function yoast_og_img( $classes = '', $link = false, $size = 'medium_large' ) {
$yoastImg = $yoastImgID = $post_thumb = false;
$before = $after = null;
$yoastImg = get_post_meta( get_the_ID(), '_yoast_wpseo_opengraph-image', true);
$yoastImgID = attachment_url_to_postid( $yoastImg );
$post_thumb = has_post_thumbnail( get_the_ID() );
if( $yoastImg || $yoastImgID || $post_thumb ) {
if( $link === true ) {
$before = '<a href="'. get_the_permalink() .'" tabindex="-1" aria-hidden="true">';
$after = '</a>';
}
if( $yoastImgID ) {
$img = wp_get_attachment_image( $yoastImgID, $size, false, [ 'alt' => '', 'loading' => 'lazy', 'class' => $classes ] );
} elseif( $yoastImg ) {
$img = '<img src="'. $yoastImg .'" alt="" loading="lazy" class='. $classes .' />';
} elseif( $post_thumb ) {
$img = get_the_post_thumbnail( get_the_ID(), $size, [ 'alt' => '', 'loading' => 'lazy', 'class' => $classes ] );
}
echo $before . $img . $after;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment