From WordPress post to Facebook easily and without plugins

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:

https://developers.facebook.com/tools/debug/og/object/

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 <head> section?

By adding this function into your functions.php file located in your theme folder:

The code is quite intuitive, just notice I used get_the_excerpt function rather than the_excerpt because get_the_excerpt returns the excerpt without any <p> tag.

And here you go with your post nicely shared on Facebook.