≡ Menu

Using Drupal Taxonomy to Control Module Display

Some time ago, I was building some modules for a Drupal project.  I wanted an easy way to control whether a particular module was displayed for a particular content item – a way of dynamically determining module visibility per page/post/whatever.  I searched high and low and couldn’t find anything, so I wrote it myself.  Some of you may be struggling the same way, so below is how I did it.

  1. Activate the taxonomy module (it’s part of the core install and may already be enabled for you).
  2. In the administration area, content management, taxonomy, create a new vocabulary.  Add a term to this vocabulary for each module for which you want to control visibility.  For example, if you’ve written modules DoIt and DoItAgain, I’d add terms ‘Do It’ and ‘Do It Again’ without the single quotes.
  3. Choose the content type for which you want this vocabulary to be available.  Make the vocabulary a multiple select.
  4. Download, install, and enable taxonomy hide module.
  5. In the taxonomy hide module settings, choose the vocabulary you created above.  This will prevent those annoying term tags from displaying on your content.
  6. Editing the content that should display your modules. You’ll have a multiple select list with all your taxonomy terms listed.  Choose the modules you want to display (i.e. ‘Do It’ and ‘Do It Again’) on each particular content item.
  7. In your module code, add this method:
    /**
    Examines the taxonomy of the calling node to determine if a module should be displayed.
    *
    @param string $moduleLabel The taxonomic label the module requires for display.
    @return true if the node is labeled with $moduleLabel, false otherwise
    */
    function _ShouldDisplay($moduleLabel)
    {
      $shouldDisplay = false;
      if (arg(0) == 'node' && is_numeric(arg(1)))
      {
        //if the arguments are legit, load up the node
        $nid = arg(1);
        $node = node_load(array('nid' => $nid));

      $terms = taxonomy_node_get_terms($node);
        //examine the terms.  If find $moduleLabel, return true;
        foreach($terms as $t)
        {
          if ($t->name == $moduleLabel)
          {
            $shouldDisplay = true;
          }
        }
      }
      return $shouldDisplay;
    }

  8. In your module code, in the _block method, wrap all the output inside a conditional like this:
    if (_ShouldDisplay('Do It'))
    {
      //all the output work here
    }

    where ‘Do It’ is the taxonomy term you defined for this module above.
  9. Save your module.
  10. In the blocks screen, drag your block module to a region (left sidebar, content, footer, etc.)

Now, when a content item is requested, your module will check the taxonomy terms for that content item.  If your module’s term is listed in the terms, your module will display.  If not, it won’t.