Choose an Open Graph Image with WordPress

Facebook Like

Facebook uses it’s Open Graph technology along with specific Open Graph meta tags to get information about pages with the iconic Like button on them. These are documented extensively on ‘Facebook Developers‘ and are introduced well by David Walsh on his blog.

The basics of the Open Graph meta tags are very simple and are shown below.

HTML

<meta property="og:site_name" content="Super Awesome Blog">
<meta property="og:title" content="Page Title">
<meta property="og:type" content="article">
<meta property="og:url" content="http://www.example.co.uk/">
<meta property="og:description" content="Simple Into...">
<meta property="og:image" content="/rock.jpg">

The Problem#

If the og:image is not specified then Facebook will try to select what it thinks is the best image on that page, not always successfully, so it’s always good to specify which image you want. With WordPress, and many other content management systems, it’s very difficult to specify custom fields – like an Open Graph image field for instance – without too much coding.

This problem was resolved with WordPress 2.9+ with the introduction of Feature Images. If you are using a custom theme (like I am) you will need to add this line to your functions.php to enable this feature:

add_theme_support('post-thumbnails');

Within your header.php we are then creating a simple function to check to see if this particular post has a Feature Image, if it does return it the URL of it.

PHP

<?
function getFeatureImageURL()
{
	if ( has_post_thumbnail($post->ID) )
	{
		$image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'single-post-thumbnail' );
		$url = $image[0];
	}
	else
	{
		// Back-up Image
		$url = "/images/feature.jpg";
	}
	return $url;
}
?>

Then simply call this function within your og:image meta tag.

HTML

<meta property="og:image" content="<? echo getFeatureImageURL(); ?>">

Once that is all setup, on any new posts just choose an Image to be your Feature Image within WordPress and it will be your Open Graph Image as well.

Also, for some extra reading I would recommend checking the WordPress Codex on Thumbnails and this support query to get the thumbnail URL.

Hope it helps!