Opengraph Image From Featured, Inline, or Attached

For opengraph and similar social sharing protocols, you’ll want to include graphics with your post and pages whenever possible for blatantly obvious reasons. Often these images are scraped from the webpage and made selectable by the share’r, which is why you’re able to specify which image you’d like to show when shared.

Sometimes (and with some WordPress setups) it’s hard to say whether the post will have a featured image, an inline image, an attached image, a gallery of images, or none at all. Furthermore, some featured images are on the webpage but shown with CSS instead of scrap-able <img alt=“” /> tags.

For that problem, I wrote this solution:

Where logo.png is your fallback image, if your post/page has nothing else. You can change the order of the if/else conditions to prioritize what you’d like (i.e. attached images to be found before inline images).

Pro tip of the day: Need more images on your text-heavy blog? unsplash.com.


Leave a Reply

%d bloggers like this: