Submitted by bluegray on

Here's how you add a Google +1 button to the contextual links of a node in Drupal 7.

Create a custom module and add the following:

// Add +1 button javascript to footer
function hook_preprocess_html(&$vars) {
  drupal_add_js(" (function(d, t) {
                    var g = d.createElement(t);
                    s = d.getElementsByTagName(t)[0];
                    g.async = true;
                    g.src = 'https://apis.google.com/js/plusone.js';
                    s.parentNode.insertBefore(g, s);
                    })(document, 'script');",
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 99)
  );
}
 
// Add +1 button to contextual links
function hook_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'blog' && $view_mode == 'full') {
      $links['plus_one'] = array(
        'title' => '<g:plusone href="'. url('node/' . $node->nid, array('absolute' => TRUE)) .'" size="medium"></g:plusone>',
        'html' => True,
        'attributes' => array('class' => 'plus_one_button'),
      );
      $node->content['links']['plus_one'] = array(
        '#links' => $links,
      );
  }
}

Or to validate as html5 you can use:

<div class="g-plusone" data-size="standard" data-count="true"></div>

This is just a simple example. First the +1 javascript is loaded in the footer by the drupal_add_js function in the preprocess_html hook. Then a link item is added to the node content in the node_view hook.

For more on adding the +1 javascript from google, see the Google +1 button code generator. Some tips and workarounds for certain problems with the standard code can be found in this review.

Comments

In my node.tpl.php file i

Alex's picture

In my node.tpl.php file i have

if ($links):
  ?>
    <div class="link-wrapper">
      <?php print $links; ?>
    </div>
  <?php endif; ?>

I tried this method and its not working for me. Links section just not showing.

Add new comment

Basic HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • You can enable syntax highlighting of source code with the following tags: <code>, <pre>, <c>, <cpp>, <css>, <drupal6>, <drupal7>, <html4>, <html5>, <java>, <javascript>, <php>, <python>.
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.