Dynamically / programatically create views filters

Taken largely from danpolant.com/dynamically-creating-views-in-drupal but with a different example.

This code uses an existing view 'my_custom_view' and adds 2 filters using 'add_item'. One filter is a simple taxonomy term id, and the other is a term id with depth = 1 from a specific vocabulary.

  $view = views_get_view('my_custom_view');
  $options = array('value' => 15);
  $view->add_item($view->current_display, 'filter', 'taxonomy_index', 'tid', $options, 'tid');
  $options = array(
     'value' => 10,
    'type' => 'select',
    'vocabulary' => 'my_vocabulary',
    'hierarchy' => 1,
    'depth' => 1
  $view->add_item($view->current_display, 'filter', 'node', 'term_node_tid_depth', $options, 'term_node_tid_depth');

It's also possible to alter existing properties using 'get_item' and 'set_item', but I had caching issues with this type, because the original view would have the filters already set (instead of really adding them dynamically with add_item).

  $filter = $view->get_item($view->current_display, 'filter', 'term_node_tid_depth');
  $filter['value']['value'] = 10;
  $view->set_item($view->current_display, 'filter', 'term_node_tid_depth', $filter);


  if ($view->result) {
    $count = count($view->result);
    $html = $view->render();
  } else {
    // no results

As said in original article, the best way to create these dynamical views is by examining and export of a view with the filters already added through the UI.


This is the company blog of
Drupal specialist Merge.nl

We are located in Breda (Netherlands) and build websites using Drupal. More about us.

Content on this blog is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Netherlands License.

Creative Commons License

Recent Comments