Last updated July 24, 2010. Created by kiko on December 2, 2009.
Edited by dawehner. Log in to edit this page.

The problem to solve is create a view that lists the nodes under a given term or under any of his related terms

The steps to follow:

1.- Create a view at www.example.com/admin/build/views/add
2.- Choose "View Type: node"
3.- Select the desired filters and fields
4.- At "Arguments" add "Taxonomy: Term ID"
5.- At "Validator Options" select "PHP Code" and paste this one:

$list = array($argument);
foreach (taxonomy_get_related($argument) as $term) {
  $list[] = $term->tid;
}
$handler->argument = implode('+', $list);
return TRUE;

6.- Below the "Validator Options" select "Allow multiple terms per argument"

And that's it. The view will now list a node if it's tagged with a taxonomy term or with any of the related terms.

A variant of this problem is to list the node if it's tagged with a taxonomy term AND with the related terms. The steps are the same replacing the row:
$handler->argument = implode('+', $list);
by
$handler->argument = implode(',', $list);

Check the full issue here #604624: Showing the nodes under a taxonomy term AND under the related terms

If you need to filter out terms of a certain vid you can change the code to:

$list = array($argument);
$vids = array(1);
foreach (taxonomy_get_related($argument) as $term) {
  if (in_array($term->vid, $vids)) {
    $list[] = $term->tid;
  }
}
$handler->argument = implode('+', $list);
return TRUE;

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

This is a really terrific slice of code - very much needed.

However, it was creating errors for me if an empty set was returned - so I added error handling to it. There might be far simpler ways to accomplish this, but the following works for my setup. Please note: I am no PHP programmer so folks are advised to test this thoroughly before using it.

I tweaked it to this:

$tid = $argument;
$terms = taxonomy_get_related($tid);
if(count($terms) > 0) {
foreach ($terms as $term) {
$list[] = $term->tid;
}
$handler->argument = implode(',', $list);
return TRUE;
}
else {
return FALSE;
}

Can this work the same way with contexts?
If I create a "Content Pane" view, what is the correct way to collect all the taxonomy terms and send them to my view?

My use case is as follows:
I have products (content-type: product) tagged with terms in a catalog (my vocabulary).
I also have accessories (content-type: accessory) tagged with the terms from the same catalog.

Thanx for this!

________________
Live fast die young