An easier way to add contextual links in Drupal 7

Contextual links are a great new feature of Drupal 7. Basically, links are added to various elements of the page to make it easy for site editers to make changes to whatever content they currently see.

By default, the contextual module smartly adds links that it finds in the normal Drupal menu system. But what if you want to add some links of your own? You have a few options: First, you could add contextual links using the normal menu system or similarly you could use a hook_menu_alter function as described in this blog post.

But there is an easier way...

The contextual module provides an alter hook that can be used to add links whereever you need them. Here is an example:

function MYMODULE_contextual_links_view_alter(&$element, &$items) {
  // This hook is called for EVERY set of contextual links
  // on a page.  We first want to check the $element to make
  // sure we are adding a link to the correct list of contextual
  // links. In this case we only want to add a link to blocks
  // created by the "search" module. We just add links using the
  // same array structure as is used by theme_links.
  if (isset($element['#element']['#block']) && $element['#element']['#block']->delta == "site_tweets-site_tweets_block") {
    $element['#links']['social-networks'] = array(
      'title' => 'Edit social network links',
      'href' => url('/admin/config/system/site-information', array('absolute' => TRUE)),

And voila...