Tell Facebook Which Image to Share

Published on May 23rd, 2011
Creating a merged image, jigsaw puzzle style!

So you just wrote 'The Best Blog Post EVER.' You have a catchy tagline, some witty prose, and an awesome image (like the one above). You also have some social tools setup because (clearly) everyone is going to want to share your article as well. All goes well until...

...you decide to let facebook pick the image for you. 
PS, you should definitely check out the above linked article. Chris Brogan is one of my favorite bloggers and I learn a ton from him (hence the sharing of his post!)

Facebook is pretty clever and can usually get the right image. And if you go to facebook and actually insert the URL in the share window, it'll let you select through the thumbnails. There are two points of failure: lazy fans and hitting the like button from the website itself. In both instances, you're not going to get as much mileage out of your carefully selected image.

Help Facebook, Help You

Instead of relying on luck and a psychic facebook script, why not simply help facebook pick the correct photo? They even tell you how to do it. Warning: some mildly geeky stuff is ahead, so you've been warned.

All you need to do is place a single line of code (see example below) in the head section of the HTML page.

If you have a statically created site (ie no CMS), you would simply go page by page and add this line of code while carefully selecting the exact image you want to display from each page. The end results in facebook would look something like this.

Much better!

The Drupal Way

Most likely, you're not creating your own webpages by hand. If you're blogging, your most likely using wordpress (if you're a wodpress user, hang on and I'll come back to you at the end). I happen to use Drupal because I tend to code sites requiring a lot more complexity and the Drupal framework allows gives me all the tools I need to make this happen. The best way to start is using the preprocess hooks, specifically the hook_preprocess_page() hook because we only need to specify a single image on a given page and therefore hook_preprocess_node would be inappropriate or require too much additional checking.

Let's suppose our theme's name was mytheme. And let's also suppose that I'm primarily using the default content type in Drupal 7 (article) using a simple image field. The final code would look something like this.

function mytheme_preprocess_page(&$vars){
  global $base_url;
  $img = $base_url.base_path().path_to_theme()."/logo.png";
  if($vars['is_front'] != TRUE){
    if(isset($vars['node']->field_image['und'][0]['uri'])){
      $img = file_create_url($vars['node']->field_image['und'][0]['uri']);
    }
  }
  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      "property" => "og:image",
      "content" => $img,
    ),
  );
  drupal_add_html_head($element,'facebook_share_image');
}

Let's break this down. The mytheme_preprocess_page() function is called by Drupal to create and/or modify any variables before the entire page is stitched together with all the parts. &$vars is simply a collection of variables that Drupal is using to create this page (e.g. which template file to use, whether or not this is the homepage, what regions are to be displayed, etc).

Strategy

On the homepage, we can have a ton of photos from a bunch of different pieces of content, so it can be somewhat difficult to choose the right one. Plus, if someone is sharing the homepage on facebook, it's probably best to stick with something that more generally describes your entire site versus a single post. Therefore I want to show the logo if someone shares the homepage. If a person decides to show one of my articles, I'd like to show that image instead. So I first set the default logo image.

$img = $base_url.base_path().path_to_theme()."/logo.png";

But then I need to test if we're on the homepage.

if($vars['is_front'] != TRUE){ **More Code In here** }

If we're not on the homepage, I still need to make sure I wasn't lazy and I associated an image with this article

if(isset($vars['node']->field_image['und'][0]['uri'])){ **More Code In here** }

Thankfully, I did include an image this time. So we can get the image path from the node

$img = file_create_url($vars['node']->field_image['und'][0]['uri']);

So now I'm feeling all pumped knowing I'm about to tell facebook exactly which image they should be using when someone shares my article. This is a big plus for me and all my millions of potential (and dozens of actual) visitors a month! Now I just need to actually inject this into the header. This is done through the drupal_add_html_head() command. Now because Drupal is so smart in how it separates data from theming (allowing other modules and themes to alter the actual display given a set of data). Don't less this scare you. It's super simple. Again, the target is this:

So we create an element that uses these variables and values as such

$element = array(
  '#tag' => 'meta',
  '#attributes' => array(
    "property" => "og:image",
    "content" => $img,
  ),
);

So we're using a metatag and it's attributes are property and content with the values of 'og:image' and 'image.jpg' respectively.

We're now done, and can bask in the glory known as image sharing on facebook. Be sure to test it out, maybe even on this page (hint hint :)

Wordpress

As I stated above, I'm not entirely sure how wordpress works with its page rendering system and whether they have preprocessing hooks like Drupal. If there is a way to scan a post and find an image when viewing a full post, you'll simply follow steps similar to the ones above. If anyone knows of these functions, I'll be happy to post a little update with the instructions on this page.

How's Your Site Doing?

When people click on the social media share tools on your site, does it look right to you? If not, should you use a different set of tools (ShareThis versus Sexy Bookmarks) or will a simple tweak on your website help?

Additional Links

Thanks for reading! If you enjoyed this, can I ask you for a favor?

I would like the opportunity to connect with you on an ongoing basis with the intention that I continue to provide you with valuable information and insights to help transform your life personally and professionally. To that end, it would mean a lot to me if you performed one or more of the following.

  1. Sign up for my newsletter to get new articles sent right to your inbox.
  2. Buy my book, Winning the Lottery Within.
  3. Follow me on Twitter or connect with me on LinkedIn. Don't forget to say hi!
  4. Contact me to setup a free, 15-minute consultation.
  5. Share this article with anyone that might benefit from it.

Thanks again for your time and attention! It means the world to me to know that you gave me this opportunity to connect with you.

About Rick Manelius

Quick Stats: CTO of Contact Mapping. Author of Winning the Lottery Within. Graduated from MIT in '03 (BS) and '09 (PhD). Life hacker and peak performance enthusiast. This blog is my experiment in creative writing, self-expression, and sharing what I've learned along my journey. For more information, read my full bio here or contact me.