PHP contextual filters

Last updated on
21 June 2017

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

When you want to do more advances contextual filtering you could use PHP contextual filter code.

Example:
There is a questions taxonomy with a number of questions.
There is a content type with 2 term reference fields, Raised questions and Answered questions
Under each page I want a list with links to pages that answer questions raised on the page.

To get this, create a new view with a block display.

  1. Create a contextual filter, on the Answered questions field.
  2. Select Provide default value.
  3. Select at Type; PHP Code.
  4. Use the following code:
  5.   $node = node_load(arg(1));
      if($node && isset($node->field_raised_questions[LANGUAGE_NONE])) {
      	foreach($node->field_raised_questions[LANGUAGE_NONE] as $term) { 
      		$terms[] = $term['tid']; 
      	}
      	return implode('+',$terms);
      } 
      else { 
      	return; 
      }
     
  6. Under More, select: Filter to items that share any term.

Here is screenshot of one of example of taxonomy.

Contextual Filter

Help improve this page

Page status: No known problems

You can: