[Drupal] How to change the Order of Calling Hook in Drupal 7?

| | 1 min read

It was not easy to change calling order of hook implementations in Drupal prior to version 7. From Drupal 7 onwards you can control the order of hooks called for different modules. To accomplish it, there is a new hook introduced in Drupal 7. It is hook_module_implements_alter().

Within this hook you will get list of functions for a particular hook that each module implements and the hook name. The implemented function will be called in the order. So, if you alter the order of functions in that array then it will effect the calling order of that functions.

Here, as an example, we are ensuring that implementation of hook_mail_alter() in mymodule will be called after all other modules. So, it can do some final modifications to all mails generated from the system.

function mymodule_dev_module_implements_alter(&$implementations, $hook) 
  if ($hook == 'mail_alter') {
      // It is to ensure that hook_mail_alter of this module is called
      // after all other hooks
      $mymodule_hook = $implementations['mymodule_hook'];
      if (isset($mymodule_hook)) {
        // Then add it back, so it will be at the end of hook array
        $implementations['mymodule_hook'] = $mymodule_hook;

Similarly, you may change order functions by moving them backward or forward within $implementations array to get desired calling order of that particular hook.