[SOLVED] How to Programmatically Create Menu Tabs?

December 19, 2017 - 17:43

For a recent project, I had a requirement to implement menu tabs in Drupal 7. Let see what are the necessary code for the same. First I created menu tabs in .module file using hook_menu() with the following codes.

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['path']= array(
    'title' => t('Create menu tab in your page.'),
    'page callback' => 'first_tab',
    'access callback' => TRUE,
    'weight' => 0,
  );

  $items['path/firsttab'] = array(
    'title' => t('Create first tab.'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'page callback' => 'first_tab',
    'access callback' => TRUE,
    'weight' => 0,
  );

  $items['path/secondtab'] = array(
    'title' => t('Create second tab'),
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'second_tab',
    'access callback' => TRUE,
    'weight' => 1,
  );

  $items['path/thirdtab'] = array(
    'title' => t('Create third tab'),
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'third_tab',
    'access callback' => TRUE,
    'weight' => 2,
  );

  return $items;
}

Then I wrote the necessary page callback functions for the corresponding tabs.

/**
 *  First tab.
 */
  function first_tab() {
  $str = t('Hi this is first tab');
  return $str;
}

/**
 *  Second tab.
 */
  function second_tab() {
  $str = t('Hi this is second tab');
  return $str;
}

/**
 *  Third tab.
 */
  function third_tab() {
  $str = t('Hi this is third tab');
  return $str;
}

Similar to the above, you can create more tabs and add other functionalities for each page. Here 'MENU_DEFAULT_LOCAL_TASK' and 'MENU_LOCAL_TASK' in menu type specification is important. The main page tab should be specified as 'MENU_DEFAULT_LOCAL_TASK'. Hope this is useful, contact us for further assistance.

Get Drupal updates straight to your inbox

To prevent automated spam submissions leave this field empty.

Post your comments / questions