Drupal 7: Secret to using hook_menu_alter

Are you trying to use hook_menu_alter in Drupal 7 and finding that hook_menu_alter is not appearing to have any effect? There is a reason. Hook_menu_alter is not called every time you run your site. Hook_menu_alter only runs when the menu module is initialized or a menu is initially constructed. If you have an existing menu and you would like hook_menu_alter to affect that menu, you must do a menu rebuild. In theory, there are two trivial ways to do this. However, the 2 trivial methods may not work for you. The trivial methods are:

  • Use Devel module option to request menu rebuild
  • Use drush to request menu rebuild

However, these 2 methods may not be convenient for you. I know that right now (8/2/2014), Devel will not run correctly on my install because there appears to be problem with the current combination of devel, devel_theme & simplehtmldom that is currently available seem to crash my install. At the same time, drush is inconvenient for the install I have available. My solution involved creation of a simple file that will force the menu rebuild.

To do a menu rebuild programattically:

  • Create a file in your site’s base directory, perhaps menuRebuild.php
  • Include the following code in the new file
    
      <?php
      
        chdir("< your-root-directory >") ;
        define("DRUPAL_ROOT", getcwd());
        require_once("./includes/bootstrap.inc") ;
        drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL) ;
        // Rebuild
        menu_rebuild() ;
        echo "rebuilt" ;
    
      ?>
    
    
  • run the file … the menu will be built.

Leave a Reply