Harnessing the power of Open Graph


Here's another good example of how out of tune I've been with programming for a world filled with social media.

I've recently noticed that when I was pasting a link to one of my articles on Instagram or Twitter, the social media sites have been grabbing whatever they can to generate a preview. In my case, it usually ended up being my logo, the title of the post, and the permalink to the post. Twitter didn't even create a preview at all. Here's what it looked like when I pasted it into a direct message on Instagram:

Before Open Graph

So, like all old people, I turned to Google and found out about the Open Graph Protocol. This internet protocol was created by Facebook, introduced in 2010, and it is basically meant for promoting integration between Facebook and other social media sites (like Instagram, Twitter, etc) by making them into "graph" objects with the same functionality as Facebook objects.

I've integrated this now into my site--I'll explain below--and as you can see, the preview to the same article is now displaying exactly what I want it to. The first image found in the article, followed by the title and the first 100 characters of the article body:

After Open Graph

Here's how I did it. First, I found a piece of script to extract the first image from a body of HTML, in my case, from the body of my article. If an image is not found in the article, it will revert to displaying the logo.

$html_entry = $converter->ConvertToHtml($entries[0]['Body']);
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $html_entry, $image);
$first_img = $image['src'];
if ($first_img)
	$og_img = $first_img;
	$og_img = $page->logo_url();

I then create the Open Graph object and pass it to the templating system (Smarty):

if ($first_img)
	$og = array(
		"type" => "entry",
		"image" => $og_img,
		"title" => $entries[0]['Title'],
		"description" => substr(strip_tags($html_entry),0,100) . "...",
		"url" => $page->base_url() . $log->log_base() . "/" . $entries[0]['PermaLink']

The page header template waits for an Open Graph object to come in, and when it does, it populates the meta tags. These meta tags are what social media sites look for to create the previews. If they exist, they'll be used. If they don't exist, the media sites will auto-generate them.

{if $og}
	<meta property="og:type" content="{$og['type']}" />
	<meta property="og:image" content="{$og['image']}" />
	<meta property="og:title" content="{$og['title']}" />
	<meta property="og:description" content="{$og['description']}" />
	<meta property="og:url" content="{$og['url']}" />

There you have it. Another thing you've most likely never thought twice about. Now when you look at a preview created after you paste a link, you will know that it is because the social media platform you're pasting it to is going out to grab these Open Graph objects in the site you're linking from. 😄