6

How to set programmatically multiple arguments for views contextual filters?

I can do it with one argument, it works great, but not with multiple arguments.

I want to select all nodes created by a list of people, but views only takes first in array into consideration:

$array = array(3250,32);
$view = views_get_view('myview');
$view->set_display("myblock");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render(); 

Am I doing something wrong?

5 Answers 5

11

First you should set this option: View → Advanced → Your Contextual Filter → More → Allow Multiple Values. Then when passing array should be with '+', so, your example:

$array = array('3250+32');
$view = views_get_view('myview');
$view->set_display("myblock");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render(); 
2
  • 1
    What hook would you use to implement this...hook views_pre_view? Commented Mar 23, 2015 at 11:59
  • 1
    The questioner asked for multiple contextual filters, not one multi-valued contextual filter.
    – fishfree
    Commented Oct 15, 2015 at 2:54
6

If you're simply looking to render the view with its arguments (and don't need to do any more work on it), you can just call views_embed_view(). It's called like so:

<?php print views_embed_view($view, $display, $arg1, $arg2, ...); ?>

The $view and $display are the machine names of same. See the above-linked documentation for details.

2
  • views_get_view_result works the same : views_get_view_result($view, $display, $arg1, $arg2, ...); Commented Apr 28, 2016 at 15:47
  • views_get_view_result returns an array of each view item as an object.
    – dresh
    Commented Jul 25, 2019 at 11:36
1

Another one approach, which proved to be quite useful:

$array = array('3250', '32'); 
$view = views_get_view('myview');
$view->set_display("myblock");
$view->pre_execute($array);
$view->execute();
$content = $view->render();

pre_execute() method of view object accepts arguments, that will be passed to corresponding contextual filters. E.g. '3250' will be passed to the first contextual filter, '32' - to the second one.

More info about method here.

1
  • Please add some explanation to the code shown in this answer. Not doing so puts your answer at risk of being deleted as a low quality answer. Commented Mar 24, 2017 at 12:29
0

are you sure your view is looking for integer values here? try this:

$array = array('3250','32'));

0

Also you can replace this $array = array(3250,32); to $array = array('3250,32');

1
  • As far as I know view accept multiple values for contexual filters only in this formats 'id1+id2' or 'id1,id2'. Just try. Commented Feb 13, 2015 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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