Share Your Posts on Facebook With a Preview Image and a Description

Share Your Posts on Facebook With a Preview Image and a Description

Tutorial Details
  • Program: WordPress
  • Version: 2.9 or higher
  • Difficulty: Intermediate
  • Estimated Completion Time: ~ 15 mins

In this tutorial we will write a plugin to set, for each post of our blog, an image and a short summary that will be shown on Facebook every time a post is shared. To do this, we will use two WordPress core features: a Featured Image for the image preview and the Post Excerpt for the description.


Step 1 Creating the Plugin

Create a new file called facebook-share-and-preview.php. Open it your favourite text editor and paste the following code:

<?php
/*
Plugin Name: Facebook Share and Preview
Version: 1.0
Plugin URI: http://www.studio404.it/
Description: Adds a Share link to every post and set an image and a description for Facebook.
Author: Claudio Simeone
Author URI: http://www.studio404.it/
*/
?>

Save the file in your /wp-content/plugins/ directory and activate it on the Plugins admin page.


Step 2 Activating Featured Images

From version 2.9 WordPress allows you to set a featured image for each post, but this useful functionality must be supported by your theme. So, open your Add New Post page and check if the Featured Image box is available:

If you don’t see the Featured Image box, add the following line to facebook-share-and-preview.php:

add_theme_support('post-thumbnails');

We also set a custom image size. According to Facebook guidelines:

The thumbnail’s width AND height must be at least 50 pixels, and cannot exceed 130×110 pixels.

A 90×90 pixel image will work well.

add_image_size('fb-preview', 90, 90, true);

Now WordPress will automatically create a Facebook thumbnail for every featured image.


Step 3 Getting the Featured Image and the Excerpt

We need two functions to get the Featured Image and the Post Excerpt:

// Get featured image
function ST4_get_FB_image($post_ID) {
	$post_thumbnail_id = get_post_thumbnail_id( $post_ID );
	if ($post_thumbnail_id) {
		$post_thumbnail_img = wp_get_attachment_image_src( $post_thumbnail_id, 'fb-preview');
		return $post_thumbnail_img[0];
	}
}

// Get post excerpt
function ST4_get_FB_description($post) {
	if ($post->post_excerpt) {
		return $post->post_excerpt;
	}
	else {
		// Post excerpt is not set, so we take first 55 words from post content
		$excerpt_length = 55;
		// Clean post content
		$text = str_replace("\r\n"," ", strip_tags(strip_shortcodes($post->post_content)));
		$words = explode(' ', $text, $excerpt_length + 1);
		if (count($words) > $excerpt_length) {
			array_pop($words);
			$excerpt = implode(' ', $words);
			return $excerpt;
		}
	}
}

Step 3 Adding Facebook Metatags to the Single Post Page

Now we write a function that gets the post’s Featured Image and the Post Excerpt and add them to the <head> section of the single posts pages.

If both Featured Image and Post Excerpt are not set, the tags will not be displayed.

function ST4FB_header() {
	global $post;
	$post_description = ST4_get_FB_description($post);
	$post_featured_image = ST4_get_FB_image($post->ID);
	if ( (is_single()) AND ($post_featured_image) AND ($post_description) ) {
?>
  <meta name="title" content="<?php echo $post->post_title; ?>" />
  <meta name="description" content="<?php echo $post_description; ?>" />
  <link rel="image_src" href="<?php echo $post_featured_image; ?>" />
<?php
	}
}

To write the metatag code in the <head> section of our blog we use the wp_head action hook:

add_action('wp_head', 'ST4FB_header');

Template Troubleshooting

Make sure that in the header.php template file there is:

<?php wp_head(); ?>

before the </head> tag. If not, add it.


Step 4 Add Facebook Share Link to the Single Post Page

In your theme, open your content-single.php template file and add this where you want the link to appear:

<a href="https://www.facebook.com/sharer.php?u=<?php echo urlencode(get_permalink($post->ID)); ?>&t=<?php echo urlencode($post->post_title); ?>">Share on Facebook</a>

For example, if you want to add the link after the post content:

<div class="entry-content">
<?php the_content(); ?>
<p><a href="https://www.facebook.com/sharer.php?u=<?php echo urlencode(get_permalink($post->ID)); ?>&t=<?php echo urlencode($post->post_title); ?>">Share on Facebook</a></p>
</div><!-- .entry-content -->

Template Troubleshooting

In this tutorial we refer to the WordPress default template: Twenty Eleven. Since the structure of every WordPress theme is different from one theme to another, you have to identify which file serves the Single Post page in your theme.

You can find two useful pages on the WordPress Codex: the Template Hierarchy and The Loop in Action. If you still have difficulties finding the right file, you can contact your theme’s author.


Final Result

Now you can write your post and add a Featured Image and an Excerpt:

This is the published post with the Share on Facebook link:

And once you click the Share on Facebook link, this will be the Facebook preview window:

Now you have some control over how your posts are displayed on Facebook when your reader’s share them. Let us know in the comments if you found this useful.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.nicksolly.co.uk Nick Solly

    Thanks for the tutorial, will be using this on my own site. Quick question – what happens if there is no featured image? Are you left with a blank box or is it not shown?

    Thanks

    Nick

    • http://www.inspiredworx.com Huw Rowlands

      @Nick; You could always add in an if statement, so that you have a default image just in case.

  • Pingback: Share Your Posts on Facebook With a Preview Image and a Description | Shadowtek | Hosting and Design Solutions

  • http://lemondedereggie.fr Reggie368

    Bookmarked !

    Thanks for this tutorial !

  • Thomas

    Why not use the open graph objects, that would make way more sense since you are targeting facebook. Here is an example for what I use from a Norwegian PS Vita review article:

    <meta property=”og:title” content=”Vi tester Sony PlayStation Vita – Review” />
    <meta property=”og:site_name” content=”TechStorm” />
    <meta property=”og:description” content=”Ventetiden var lang, men endelig så kommer den nye håndholdte konsollen fra Sony, PS Vita, til Norge. PlayStation Vita, som allerede i desember 2011 ble lansert i Japan, skal…” />
    <meta property=”og:type” content=”article” />
    <meta property=”og:url” content=”http://www.techstorm.no/2012/02/18/test-playstation-vita-review-omtale/” />
    <meta property=”og:image” content=”http://www.techstorm.no/wp-content/uploads/2012/02/21-150×150.jpg” />

  • http://www.paulund.co.uk Paul

    Looks like from this tutorial that if there is no featured image then you won’t add the meta tags.

    I would use a default use for facebook and just bring that in if no featured image exists. Is there a reason why you haven’t used the facebook open graph tags?

    Thanks

  • http://freakify.com Ahmad Awais

    Using open graph standards is always preferred, though a nice tutorial.

    • http://www.studio404.it Claudio Simeone
      Author

      Thanks Ahmad,

      I didn’t use Open Graph in order to keep the tutorial as simpler as possible.
      If you want to use OG tags, you have to add an additional namespace to the <html> tag and I wanted to minimize the changes to the template.

  • http://www.archer-group.com/ Bart Hook

    Great tutorial. I just completed something very similar for a client. This would have saved me some time.

    As others have mentioned above, I strongly suggest using the open graph meta tags. It guarantees that the post will be shared correctly in Facebook. Additionally it will work for LinkedIn’s share.

    To test that everything will work correctly, you can use this tool:
    https://developers.facebook.com/tools/debug

    Looking forward to more tutorials from you.

    Take care.

    Bart

  • Joe Pataterno

    Thanks! this is really interesting and useful.

    And yes it is very simple since no OG tags used. Good job.

  • http://diegolamonica.info Diego La Monica

    Great post Claudio!
    Clear, simple and useful!

  • Pingback: Wordpress - Plugins - Social media | Pearltrees

  • http://www.squareonemd.co.uk Elliott from the design company

    Interesting tutorial, some mixed opinions about og techniques!

  • http://pippinsplugins.com Pippin

    Nice. A couple of things I would suggest:

    add htmlentities() to the excerpt function. If you don’t, then the description meta gets invalidated when the excerpt contains double quotes.

    $text = str_replace(“\r\n”,” “, strip_tags(strip_shortcodes(htmlentities($post->post_content))));

    Second, add the conditional around the rel=”image_src” link, as suggested by others:

    <link rel="image_src" href="” />
    <?php

    • http://pippinsplugins.com Pippin

      My code got stripped:

      <?php if(has_post_thumbnail()) { ?>
      <link rel=”image_src” href=”<?php echo $post_featured_image; ?>” />
      <?php
      }

  • Pingback: Публикация записей в Facebook с миниатюрой и описанием | Wordpresso

  • Pingback: Tweet Heat - The hottest Tweets of the Month [March 2012] | Inspired Magazine

  • http://gennarodifiandra.com Gennaro

    Hi, thanks for this guide. Is possible set description generate from Platinum SEO Pack in og:description?

  • Pingback: Wordpressで投稿をプレビューと概要付きでFacebookで共有する | 備忘録

  • Pingback: 30 How to’ s.. plugins, themes, tips for WordPress | Phire Base - Graphic, Webdesign, Inspiration. Adobe & WP

  • http://www.geekandblogger.com Pavan Somu

    Most of the SEO optimized themes have this option by default.

  • Marco

    Thanks for the tutorial, but I cannot get the result you show. I use the theme you indicate, and I made the changes to header.php and content-single.php, but all I get is share on you timeline, with no picture and no excerpt.
    Any suggestion where I could get wrong?

    thx