The Wicked Coder

PHP, fun and all

Resolve thumbnail issue while sharing post on facebook.

So many of my WordPress user friends ask me this particular issue, that while sharing their blog post to facebook either they did not get any thumbnail or their post sharing displays un-relevant thumbnail image. And I remember the same issue was faced by me at the very initial stage of blogging.

Cause of the issue – No Thumbnail or un-relevant thumbnail while sharing post on Facebook

The only cause which I get to know in my R&D is “Bad coded facebook script”. So this facebook script search for all the image tags in our posts and pages, and display what it feels relevant, and even some time it stops image searching in between. As a reason we will not able to assign particular post image to facebook sharing.

Solution for the issue – Facebook share thumbnail image missing or un-relevant image thumbnail

We actually have two solutions for the issue, where one works well for the static site and another works in case of dynamic site like WordPress Blog with different posts.

Solution for the static sites

Simply add any of the bellow line of code in the <head> section of your template file

Simply add any of the bellow line of code in thesection of your template file

	

OR

Just don’t forget to update the image path in the above code.
Solution for the dynamic sites

Open function.php from your current activated theme folder in your WordPress site, and place the below code in it

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 '';
        }
        else{
               $thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
               echo '';
        }
        echo "\n";
}
add_action( 'wp_head', 'insert_image_src_rel_in_head', 5 );

Just don’t forget to update the default image path in the above code so you have to update http://example.com/image.jpg with your actual image path. So the above code will first search for the post featured image and assign that image to facebook sharing otherwise it will assign the default image to it.

If you like you can use this plugin as an alternative to the above code – Add image_src Meta Tag

The Wicked Coder © 2014