Add Open Graph Protocol meta data to your Drupal node page
Here's yet another handy and non-modular snippet to quickly add Open Graph meta datas to your <head>
tag.
A little description about Open Graph (taken from The Open Graph protocol website):
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.
Lets dive into the codes directly..
In your node.tpl.php, add the following snippet (assuming your Open Graph description is from node body):
$site_name = variable_get('site_name');<br>$og_title = $title . ($site_name ? ' | ' . $site_name : '');<br>$og_description = isset($content['body']['#object']->body[LANGUAGE_NONE][0]) ? drupal_substr(check_plain(strip_tags($content['body']['#object']->body[LANGUAGE_NONE][0]['safe_value'])), 0, 100) . '..' : '';<br>if ($page) {<br> drupal_add_html_head(array(<br> '#tag' => 'meta',<br> '#attributes' => array(<br> 'property' => 'og:title',<br> 'content' => $og_title,<br> ),<br> ), 'node_' . $node->nid . '_og_title');<br> drupal_add_html_head(array(<br> '#tag' => 'meta',<br> '#attributes' => array(<br> 'property' => 'og:description',<br> 'content' => $og_description,<br> ),<br> ), 'node_' . $node->nid . '_og_description');<br>}
EDIT:
Of course, you can add as many Open Graph meta data s possible, such as og:image
which will produce a thumbnail image when shared in Facebook.
Refer to OGP's website for more information on the types and documentation.
EDIT 2:
Thanks to mongolito404 for suggesting to use template_preprocess_node()
method.
If you want to have a cleaner and organised code, place the logic into template.php
of your theme instead.
function YOUR_THEME_preprocess_node(&$vars) {<br> if ($vars['page']) {<br> $site_name = variable_get('site_name');<br> $og_title = $vars['node']->title . ($site_name ? ' | ' . $site_name : '');<br> $og_description = isset($vars['node']->body[LANGUAGE_NONE][0]) ? drupal_substr(check_plain(strip_tags($vars['node']->body[LANGUAGE_NONE][0]['safe_value'])), 0, 100) . '..' : '';<br> drupal_add_html_head(array(<br> '#tag' => 'meta',<br> '#attributes' => array(<br> 'property' => 'og:title',<br> 'content' => $og_title,<br> ),<br> ), 'node_' . $vars['node']->nid . '_og_title');<br> drupal_add_html_head(array(<br> '#tag' => 'meta',<br> '#attributes' => array(<br> 'property' => 'og:description',<br> 'content' => $og_description,<br> ),<br> ), 'node_' . $vars['node']->nid . '_og_description');<br> }<br>}
Tags: drupaldrupal 7open graphmetametadatameta datafacebookogtitledescriptionimagenodepage