Last updated December 20, 2012. Created by peteruithoven on December 20, 2012.
Log in to edit this page.

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.

  1. To get this, create a new view with a block display.
  2. Create a contextual filter, on the Answered questions field.
  3. Select Provide default value.
  4. Select at Type; PHP-code.
  5. Use the following code:
  6. <?php
      $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;
      }

    ?>
  7. Under More, select: Filter to items that share any term.

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

Comments

Thank you, peteruithoven. This was exactly what I was looking for. I worked like a charm.

Awesome, thanks. I was trying to do all sorts of other tricky stuff to get it to work, not thinking about using PHP.

Just one question: I have "Allow multiple values" checked in the MORE tab of the contextual filter. Is there any way to reduce duplicates when working with Content: Teaser?

Nevermind! I just found the 'Distinct' option in the 'Query settings' options. Neat little feature.

I really want to confirm about Drupal best practice, that should we use PHP code in contextual filter or should we use hook_views_pre_view and pass contextual filter value their?