Make Facebook show the right image on Wordpress links you share

Posted on Aug 22, 2018

Or how to get around Facebook's inability to read my mind.

Wordpress links on Facebook

I occassionally need to post a link on Facebook back to a Wordpress site. Even though almost every other social site seems to be able to handle this simple task sanely, Facebook demands that you format your page with "Open Graph" tags or it will stubbornly refuse to show any image or if it will show an image will almost certainly display the wrong one, and not give you an option to choose the right one.

I finally got tired of this behavior and decided to fix it once and for all. To figure out what is going wrong the first stop is the Facebook Developers Sharing Debugger page:

Just paste in the URL and it will report what nit-picky bullshit it finds wrong with your page and why it won't do anything useful for you.

The first thing I tried was to set the desired image as the Featured Image in Wordpress, carefuly to delete the page cache (since I'm using a caching plugin on that site). Setting a Featured image made Facebook display an image at least but it was the wrong one.

I tried two different Wordpress plugins to solve the problem: Simple Facebook OG Image and OG both are very simple and offer no configuration options but neither seemed to do anything. To be fair only OG was certified for my version of Wordpress but despite clearing the page cache, Facebook would only see the wrong image.

Luckily I ran across this post which solved my problem.

First I had to set a custom field with name = "og_image" on the post with a value = URL to the image I wanted Facebook to display. Facebook has some requirements for the size of the image as well which is annoying - it has to be 200 x 200px minimum for one thing.

Then I needed to add a function to my theme's function.php file (you can do this in Appearance | Editor | Theme Functions but be careful!)

function insert_og_image() {

if(get_post_meta(get_the_ID(), 'og_image', true) && is_single()) {
$output = '<meta property="og:image" content="'. get_post_meta(get_the_ID(), 'og_image', true) .'" />';
}

echo $output;
}
add_action('wp_head','insert_og_image');

I'm not running Jetpack which would interfere with this method but if you are the article describes what you can do to get around it.