Feb 6, 2015

How to add hash (#) link in Drupal (7.x) menu

Below is the code which shows how we can use the hash link, once it has been declared in our custom module.

Create a module with .info and .module extensions. In your .module extension, use the below mention code.
/**
 * Implements hook_menu().
 *
 * Defines a valid link to use when creating menu items.
 */
function MYMODULE_menu() {
  $items = array();
  $items['hash_link'] = array(
    'page callback' => 'drupal_not_found',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Implements hook_menu_link_alter().
 *
 * Flags the link to be altered at runtime.
 *
 * Note: Changes here would be saved back to the database.
 */
function MYMODULE_menu_link_alter(&$item, $menu) {
  if ($item['link_path'] == 'hash_link') {
    $item['options']['alter'] = TRUE;
  }
}

/**
 * Implements hook_translated_menu_link_alter().
 *
 * Refactors the link to go to the fragment #hash_link.
 */
function MYMODULE_translated_menu_link_alter(&$item, $map) {
  if ($item['link_path'] == 'hash_link') {
    $item['href'] = '';
    $item['localized_options']['fragment'] = 'hash_link';
  }
}
Once you have activated your module, go to your menu where you want to add the hash link, for instance I would like to add hash link in my main menu so I will access admin/structure/menu/manage/main-menu/add and there I will create a menu such as "About" with path as "hash_link"

No comments :

Post a Comment