Created
July 14, 2020 17:29
-
-
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.
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 | |
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