Executing & Filtering views programmatically

Public

Sometimes you need to use views results on backend because it is easier and then you can use this snippet.

</> CopyGet raw version
php
  1. // Setting up helper variables to instantiate the view
  2. $display_id = 'default';
  3. $view_name = 'name_of_the_view';
  4. // Instantiating the view
  5. $view = views_get_view($view_name);
  6. $view->set_display($display_id);
  7. // Fetching informations about filters
  8. $filters = $view->display_handler->get_option('filters');
  9. // Overriding filters settings
  10. $filters['name']['value'] = $value;
  11. $view->display_handler->override_option('filters', $filters);
  12. // Executing view
  13. $view->pre_execute();
  14. $view->execute();
  15. // Exposing beautifully filtered results
  16. $view->result;