Community & Support

[Solved] Views, argument and PHP custom code : what am I missing?

Hi,

I have a view that returns a list of node titles of a particular content type. I'm displaying this view in a block. Now, I want to filter the results depending on the taxonomy terms of the node my block is displayed on.
Let's say my taxonomy is the following:
- Vocabulary 1 : foo
-- Term 1 : fbar
-- Term 2 : foob
- Vocabulary 2 : bar
-- Term 1 : misc
-- Term 2 : baz

When I'm visiting a node, I want to display a block in the sidebar, containing items that have one or more terms in common, but only if these terms are belonging to Vocabulary 2. So in my view parameters I've added Taxonomy: term ID as an argument, and used the following PHP snippet to provide the default argument :

$node=node_load(arg(1));
if($node->taxonomy){
  foreach($node->taxonomy as $term){
    if ($term->vid == 2) // vid of my vocabulary
     {$terms[]=$term->tid;
    } else {return;}
}
if ($terms) {return implode('+',$terms);} else {return;}
}else {return;}

This code works if the node we are visiting has only taxonomy terms from Vocabulary 2. If the node has taxonomy terms from Vocabulary 1 and Vocabulary 2, the validation fails and the results are not filtered ; I don't understand why. Am I missing something?

Thanks !

Comments

return null

As soon as you hit $term->vid != 2 your snippet returns nothing.

Just remove the else clause from the foreach loop. It's not needed. As a matter of fact, none of them are:

$node=node_load(arg(1));
if($node->taxonomy){
  foreach($node->taxonomy as $term){
    if ($term->vid == 2) {
      $terms[]=$term->tid;
    }
  }
}
if ($terms) { return implode('+',$terms); }

Thank you

Thank you, now it works as expected and I know a bit more PHP :-)

thank you so much for this

thank you so much for this code!

Thanks!

This is exactly what I needed.
Thanks so much.

ThankyouThankyouThankyouThank

ThankyouThankyouThankyouThankyouThankyou

This saved my day!

Thanks for the simple and elegant solution!