When you run a blog, you’ll often run a Facebook page too where to share your posts like I am doing with my official Facebook page. Or maybe you don’t – although you SHOULD – but you want links people share on Facebook from your blog to appear nice and well formed.
There are dozens of plugins doing this job pretty well, but I strongly prefer to write my own code to perform easy tasks rather than relying on third party software.
Follow me and you’ll create your WordPress Open Graph meta generator in 15 lines of code.
The Open Graph protocol enables any web page to become a rich object in a social graph. For instance, this is used on Facebook to allow any web page to have the same functionality as any other object on Facebook.
Facebook integrated Open Graph in 2010 allowing to decide how a third-party page is shown on Facebook when it’s shared by including some Open Graph meta tags in the
<head> part of the website’s code.
Moving From theory to real world examples, to turn your web pages into graph objects, you need to add some basic metadata to your page, but before let me show you a page which will help you a lot during the process of creating your Open Graph tags:
It’s the official Facebook Open Graph debugger which will show you how your page will look once shared on Facebook.
og:title – The title of your object as it should appear within the graph, which is your post/page title
og:type – The type of your object, mostly “article” if you run a blog.
og:image – An image URL which should represent your object within the graph, typically the featured image
og:url – The URL of your post
og:description – A one to two sentence description of your article, like the excerpt.
og:site_name – The name of your site
How can we add these meta tags into your blog
By adding this function into your
functions.php file located in your theme folder:
echo "<meta property=\"og:title\" content=\"" . get_the_title() . "\"/>\n";
echo "<meta property=\"og:type\" content=\"article\"/>\n";
echo "<meta property=\"og:url\" content=\"" . get_permalink() . "\"/>\n";
echo "<meta property=\"og:description\" content=\"" . get_the_excerpt() . "\"/>\n";
echo "<meta property=\"og:site_name\" content=\"" . esc_html(get_bloginf("name")) . "\"/>\n";
echo "<meta property=\"og:image\" content=\"http://www.emanueleferonato.com/images/emanuele_feronato_logo.png\"/>\n";
$thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), "medium");
echo "<meta property=\"og:image\" content=\"" . esc_attr($thumbnail_src) . "\"/>\n";
The code is quite intuitive, just notice I used
get_the_excerpt function rather than
get_the_excerpt returns the excerpt without any
And here you go with your post nicely shared on Facebook.