Wednesday 12 October 2011

How to set post thumbnail as image for facebook share?


When we write or read any article and if we found that it as useful then we will share it to our friends or any known persons. We will make this is to spread that useful information to all. For this we have social bookmarking sites like facebook, twitter, and digg and delicious etc.

Facebook is the popular social bookmarking site; it will have two options for Share the data. One is facebook like button to like any post and another one is facebook share button. Facebook share button works same like facebook like button.

Facebook has some set of open graph Meta tags, which are to decide which image to show.

<meta property="og:image" content="http://ruchimayam.blogspot.com/palapuri.jpg"/> is the open graph  meta tag to find the image for facebook share. This should be present in the header before </head>.When we want share any article it will check for above tag , if it is not present then it will check for the older method of specifying an image  

<link rel="image_src" href="http://ruchimayam.blogspot.com/palapuri.jpg "/>.

If neither is present then it will read the whole page and gives the all available types of images like jpeg, png, gif on that page and it will ask us to select any thumbnail image before posting the link to profile. 


To avoid the selection of images from the content and to define a particular image as thumbnail, place the following code in the header file.

<link rel="image_src" href="http://ruchimayam.blogspot.com/logo.jpg "/>

Replace the image url with your logo url and it will display the same default image for all the posts you share.

For Wordpress Sites

The above code will work if you want to use same custom image for all the posts, but if you want to use related image for individual post or page use the following code.

Copy and paste the following code in the functions.php of your theme to define the post thumbnail as thumbnail for facebook share.

add_action( 'wp_head', 'fb_thumbnails' );
Function fb _thumbnails ()
{
global $posts;
$ thumb = 'http://indianrecipe4u.com/wp-content/themes/twentyten/images/logo.png';
$content = $posts[0]->post_content; // $posts is an array, fetch the first element
$output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
if ( $output > 0 )
$thumb = $matches[1][0];
else
echo " <link rel=\"image_src\" href=\"$thumb\" /> ";
}

Replace the $ thumb variable url with the one which you want to specify as default image if there is no image in the post content.

Sometimes after placing the code also the results will not display properly, because Facebook crawler  will access your page and cache the meta information .Facebook will scrape the page for every 24 hours. To force facebook server to clear the cache immediately use Facebook Url Debugger /Facebook  Linter Tool .




No comments:

Post a Comment