Have you ever tried clicking on a Facebook Share link from a blog post just to end up with either no thumbnail, or very unrelated thumbnail showing up? This is exactly what happened to one of our client’s site. For them, we simply wrote a manual code and placed into their header.php, but while surfing through twitter we came across a better solution. In this article, we will show you how to avoid no thumbnail or unrelated thumbnail issue while sharing posts on facebook.
One of the reason why you get no thumbnail, or unrelated thumbnail is because facebook’s script is not smart enough. On each page load, it searches for all image tags and display the ones that it finds useful. Sometimes the script times out without even loading the right image. To get around this issue, facebook recommends developers to tell the script exactly which image to pick by adding a meta tag in the header. The meta tag looks something like this:
<meta property="og:image" content="http://example.com/image.jpg"/>
This works perfectly when you are running a static site, but for a dynamic platform like WordPress, we need to tweak the code a little bit to make it work. We are going to use the WordPress Post Thumbnail (aka featured image) and tell facebook script to pick that as the main image. If for some reason you did not attach a featured image to a post, then we will tell facebook to pick a default image that we have pre-selected.
You need to open your theme’s functions.php file and paste the following code within the php tags:
function insert_image_src_rel_in_head() {
global $post;
if ( !is_singular()) //if it is not a post or a page
return;
if(!has_post_thumbnail( $post->ID )) { //the post does not have featured image, use a default image
$default_image="http://example.com/image.jpg"; //replace this with a default image on your server or an image in your media library
echo '<meta property="og:image" content="' . $default_image . '"/>';
}
else{
$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
echo '<meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>';
}
echo "\n";
}
add_action( 'wp_head', 'insert_image_src_rel_in_head', 5 );
This code will add a meta tag only on single post pages with the thumbnail url in the meta tag. We have specified a default image “http://www.example.com/image.jpg”, so make sure you change that URL in the code for your image.
For those users who do not want to mess with the codes, there is a plugin for you to use called Add image_src Meta Tag
This function will solve your no thumbnail issue with facebook sharing.
Source: Staenz Web Solutions
Hi, would it be possible to adapt this script to make my own site dynamic pages show a thumbnail when posted to facebook? (I mean no WP at all). How would that be? Thank you very much
- spam
- offensive
- disagree
- off topic
Like