I have been working on Drupal 7 for almost two years now. During these two years I have worked on many hooks but hook_menu_alter() hook is the one of the mostly used one. Today i going to explain my experience with this hook.

Change theme of particular page/menu:

I have discussed this one of earlier post in detail. There we have used hook_custom_theme() hook to change theme on particular page. Instead of this we can also use hook_menu_alter() as another way to achieve same feature.

/*
 * Implements hook_menu_alter().
 */
function custom_module_menu_alter(&$items){
  // Change 'node/add/page' page to admin theme (Assume by default node/add page uses default theme)
  $items ['node/add/page']['theme callback'] = variable_get('admin_theme');
}

Change title of page/menu:

Menu provides page titles. If we are in ‘node/add/page’ then we see page title as ‘Create Basic page’ but what if we need custom title like ‘Add page’. We can achive this using below custom module.

/*
 * Implements hook_menu_alter().
 */
function custom_module_menu_alter(&$items){
  // Change 'node/add/page' title to 'Add page'
  $items ['node/add/page']['title'] = 'Add Page';
}

Customize accessing a page/menu:

For many pages/menus we restrict access to different users or on conditions. Let’s say we want restrict ‘user/register’ page in particular times.. I mean no registration will be done in 12AM - 06AM.

/*
 * Implements hook_menu_alter().
 */
function custom_module_menu_alter(&$items){
  // Restrict 'user/register' page in 12AM-05AM
  $items ['user/register']['access callback'] = '_MY_MODULE_time_access';
}

/*
 * Access callback function to restrict user registration in particular timings
 */
function custom_module_time_access(){
  // Get current time hour like 0,1,2,3....23
  $current_time_hour = date('G');
  
  // if current time is between 0 & 5 then return false
  if($current_time_hour >= 0 && $current_time_hour <= 5 ){
    return false;
  }
  return TRUE;
}

Create duplicate page/menu:

We can also use hook_menu_alter() hook if we want to create a duplicate page, a page with same functionality but with different url. Let’s say we want a url ‘add/page’ which acts same as of ‘node/add/page’.

/*
 * Implements hook_menu_alter().
 */
function custom_module_menu_alter(&$items){
  // Copy ‘node/add/page’ page to ‘add/page’
  $items ['add/page'] = $items ['node/add/page'];
}
 

comments powered by Disqus