How to make your Taxonomy Query View more flexible using Argument Handling Code

This code was very helpful for me, so I thought I should post it here for others to use.
This is PHP code to be placed in "Argument Handling Code" under "Arguments" in a taxonomy_term View that takes Term ID as its first argument.

Context: The site I wrote this for is a blog with multiple categories. The categories are implemented via a required, controlled, single vocabulary... so in other words each blog post has exactly one category. I am not sure what this code will do with other sorts of vocabularies. Feel free to post a comment if you try it out.

What it does:
- Provides an 'all' option so that 'example.com/taxonomy/all' will show you nodes for all taxonomy terms in the vocabulary
(vid=1)
- Use taxonomy term id's or term names interchangeably
(so you could do 'example.com/taxonomy/Some Category+2+3+Last Category')
- Perform AND queries with taxonomy term names, even if they have spaces

(Views does not allow you to do taxonomy queries in the form of 'example.com/taxonomy/CatA+CatB+CatC'... you can only do 'example.com/taxonomy/CatA'. Also, if you do 'example.com/taxonomy/First Category', 'First' and 'Category' will be separated even if you have a taxonomy term by that name. This code fixes that.)
- Will not mess up RSS feeds
(So in other words you still get the RSS feed associated with whatever taxonomy query you are using)

Bugs/Issues: Because my site was using a singular controlled grammar, OR queries (,) will never be needed. All I need are AND queries (+), so if you try 'example.com/taxonomy/First Category,2,3,Last Category', this code will not work and will probably mess up your page. Maybe I will add this in later. Feel free to post the modified code if you want to add this feature.

$vocab = taxonomy_get_tree(1);

// Convert 'All' into Every Category Name
if($args[0]=='All' || $args[0]=='all'){
  $args[0] = '';
  foreach($vocab as $myterm){
    $args[0] .= $myterm->name . '+';
  }
  $args[0] = substr($args[0], 0, strlen($args[0])-1);
}
else{
  $urltp = $_SERVER['REQUEST_URI'];
  for($i=1; $i<sizeof($args); $i++){
    $urltp = dirname($urltp);
  }
  $args[0] = str_replace('%2B', '+', substr($urltp, strripos($urltp, '/')+1));
}

// Convert Term Names into tid's
$names = explode('+', $args[0]);
$args[0] = '';
foreach($names as $n){
  if(is_numeric($n)) $args[0] .= $n . '+';
  else{
    foreach($vocab as $term){
      $termname = strtolower(preg_replace('/[^a-zA-Z]*/', '', $term->name));
      $givenname = strtolower(preg_replace('/[^a-zA-Z]*/', '', $n));
      if($termname==$givenname){
        $termid = $term->tid;
        $args[0] .= $termid . '+';
      }
    }
  }
}
$args[0] = substr($args[0], 0, strlen($args[0])-1);

// Return arguments
return $args;

Edit the first line if you want to use a vocabulary other than vid 1.

 
 

Drupal is a registered trademark of Dries Buytaert.