[Drupal] How to change default taxonomy term/termid path to a custom path in drupal 7

| | 2 min read

By default in drupal if we click on any taxonomy term, it will execute the taxonomy/term/% menu. We can change this default taxonomy/term/% menu path to a custom menu path. In one of my project I had a requirement to execute a custom function for my vocabulary in stead of executing the taxonomy/term/% menu and I had found a solution for this. The following are the steps to be done.

  • Implement the hook entity_info_alter. In that first get the vocabulary id of our vocabulary. Then set a uri callback function that should be executed when any of the term in our vocabulary is invoked.

    Suppose that our vocabulary id is set in the variables table with key 'categories'. Then see the following example code.

      
        /**
         * Implements hook_entity_info_alter().
         * Setting the uri callback for our vocabulary.
         */
        function mymodule_entity_info_alter(&$info) {
          if ($vid = variable_get('categories', 0)) {
            foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocabulary) {
              if ($vid == $vocabulary->vid) {
                $info['taxonomy_term']['bundles'][$machine_name]['uri callback'] = 'categories_uri';
              }
            }
          }
        }
      
    
  • Define the uri call back function added in the the hook_entity_info_alter() for our vocabulary.

    See the following example code.

        
          /**
           * Defining the URI callback function set in the hook entity_info_alter().
           * Setting the custom path for our vocabulary
           */
          function categories_uri($category) {
            return array(
              'path' => 'categories/' . $category->name,
            );
          }
        
      

The above code will change the default taxonomy/term/% menu path to a custom menu path. So by implementing hook_menu for this path we can execute our custom function to create the taxonomy term page for our vocabulary.