0

I would like a views contextual filter to only use the last argument in the url. Given the following taxonomy structure, I would want /term-a to return Term A1 and Term A2 only (which works fine). However, if the url is /term-a/term-a1 I would want only Term A1a to be returned, which isn't working, it's still returning Term A1 and Term A2

Within views, I don't see a way to use the last part of the path for the filter. I tried to remove the argument from the path and then use the following as a default argument:

$path = arg();
return array_pop($path);

Here is the sample term hierarchy:

- Term A
  - Term A1
    - Term A1a
  - Term A2
- Term B
  - Term B1
  - Term B2

Just to reiterate what is returned:

The path /term-a returns:

  • Term A1
  • Term A2

The path term-a/term-a1 returns:

  • Term A1
  • Term A2

The path /term-a1 returns:

  • Term A1a
1

One solution would be hook_views_pre_view()

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
    if ($view->name == 'view_machine_name' && $display_id == 'my_display_id') {
        $args = array(end($args));
    }
}

For a view with one contextual filter this would always set the argument to the last argument from the URL.

| improve this answer | |
  • I thought about this solution, and it may be the way to go as I need to alter the view for other things. Any idea why the Default Value PHP code wouldn't work here? – Chris Rockwell Feb 18 '15 at 17:00
  • 1
    I believe your default value won't work because it's the default value for when it's NOT in the URL, but in your case the filter value is in the URL. – thumbson Feb 18 '15 at 17:25
0

Use one view with two page displays.

The first display will take one contextual filter of /term-a

The second display will take two contextual filters. The first filter will be global null (so you can throw it away), and the second will be term-a1

| improve this answer | |
  • I see, thanks. Is there a reason you would use this route instead of getting the last argument from the path? Or are they just two equally viable solutions? – Chris Rockwell Feb 18 '15 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.