Skip to main content

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

30th Jun 2009

Mike Dixon

Senior Mind

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 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