Skip to main content

Extending the drupal context module to allow conditional contexts based on taxonomy terms

An article from ComputerMinds - Building with Drupal in the UK since 2005
30th Jun 2009

Mike Dixon

Senior Mind
Hey, you seem to look at this article a lot! Why not Bookmark this article so you can find it easily in the future?

We are loving the Drupal context module here at ComputerMinds, it puts a lovely user friendly formal front end onto creating context's for your site, something we had previously been doing with various snippets of code. If you haven't come accross the context module before then I fully recommend you have a look at this post http://www.developmentseed.org/blog/2008/apr/09/context-ui which explains all ...

Taxonomy based context

The one key element that seems to be missing from context is the ability to set the context based on taxonomy, but no fear - the context module is super easy to extend and this just gives us an excuse to have a play

The first thing we do is tell the context module that we have a new context condition, based on the taxonomy term. We borrow a sneaky bit of code from the taxonomy module to render all the taxonomy terms in a pretty array.


function context_taxonomy_context_conditions() {
  $items = array();

if (module_exists('taxonomy')) { $taxonomy = module_invoke('taxonomy', 'form_all', 1);

$items['taxonomy'] = array(
  '#title' => t('Taxonomy'),
  '#description' => t('Set this context when displaying a node within this taxonomy term.'),
  '#options' => $taxonomy,
  '#type' => 'select',
  '#multiple' => true,
);

}

return $items;
}

Now we just need to tell the context module which taxonomy term we are currently viewing, we can do that using a normal nodeapi implementation, just calling the context_set_by_condition with the appropriate condition name, and the appropriate value, and the context module will look after the rest - brilliant.


/**
 * Implementation of hook_nodeapi().
 */
function context_taxonomy_nodeapi(&$node, $op, $teaser, $page) {
  if ($op == 'view' && $page && arg(0) == 'node') {
    // Implementation of context for nodequeue.
    if (module_exists('taxonomy')) {
      foreach($node->taxonomy as $term){
        context_set_by_condition('taxonomy', $term->tid);
      }
    }
  }
}

This should really be submitted as a patch to the context_contrib module, and I will look at doing that fairly soon - but for now it should serve as a nice little intro to create your own context conditions

Hi, thanks for reading

ComputerMinds are the UK’s Drupal specialists with offices in Bristol and Coventry. We offer a range of Drupal services including Consultancy, Development, Training and Support. Whatever your Drupal problem, we can help.