Advertisement
Creative Coding

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

by

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 130x110 pixels.

A 90x90 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.

Related Posts
  • Code
    Creative Coding
    Advanced Use of Attachments in WordPress: Creating Custom Queries for AttachmentsAdvanced use of attachments in wordpress 400
    This tutorial is the second in a four part series in which you'll learn some techniques for working with images in attachments in WordPress which give you advanced options.Read More…
  • Code
    Theme Development
    Custom Controls in the Theme CustomizerTheme customizer custom control 400
    In the last article, we explored the advanced controls available in the Theme Customizer, and how to implement them. We’re going to look at how to create our own custom control, allowing you to choose which Category of Posts are displayed on the home page. To get started, download version 0.6.0 of our Theme Customizer Example.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme from Static HTML: Creating an Archive TemplateCreating wordpress theme from html 400
    If you've been working your way through this series, you now have a functioning theme with two page templates. The steps I've demonstrated to this point are: preparing your markup for WordPress converting your HTML to PHP and splitting your file into template files editing the stylesheet and uploading your theme to WordPress adding a loop to your index file adding meta tags, the wp_head hook and the site title and description to your header file adding a navigation menu adding widget areas to the header and sidebar adding widget areas, a colophon and the wp_footer hook to the footer file creating template files for static pages. Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: The Footer FileCreating wordpress theme from html 400
    In this series, you've been learning how to create a WordPress theme form static HTML. Up to this point, you have: prepared your markup for WordPress converted your HTML to PHP and split your file into template files edited the stylesheet and uploaded your theme to WordPress added a loop to your index file added meta tags, the wp_head hook and the site title and description to your header file added a navigation menu added widget areas to the header and sidebar. Read More…
  • Code
    Theme Development
    Creating a WordPress Theme from Static HTML - Adding WidgetsCreating wordpress theme from html 400
    In this series, you've learned how to convert a static HTML file to a WordPress theme and edit the header file. So far you've: prepared your markup for WordPress converted your HTML to PHP and split your file into template files edited the stylesheet and uploaded your theme to WordPress added a loop to your index file added meta tags, the wp_head hook and the site title and description to your header file added a navigation menu. Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: Adding a LoopCreating wordpress theme from html 400
    In the first three parts of this series, you learned how to prepare static HTML for WordPress and to create a theme by splitting your HTML file into a set of template files and editing the stylesheet. You then uploaded your theme to WordPress and activated it. The theme still isn't displaying any content you add via the WordPress admin however; to do that you need to add a loop to your template files.Read More…