27 October 2023

How to add a filter programmatically to a view in Drupal 7 using the hook_views_pre_view alter hook. This is useful when you want to modify the behaviour of a view by adding a filter condition dynamically, based on certain conditions or criteria. The goal was to provide you with the correct code to achieve this.

Source code viewer
  1. /**
  2.  * Implements hook_views_pre_view().
  3.  */
  4. function HOOK_views_pre_view(&$view, &$display_id, &$args) {
  5. // Check if this is the view where you want to add the filter.
  6. if ($view->name == 'your_view_name' && $display_id == 'your_display_id') {
  7. // Add the filter to the display.
  8. $view->display[$display_id]->handler->options['filters']['your_filter_name'] = array(
  9. 'id' => 'your_filter_name',
  10. 'table' => 'your_table_name',
  11. 'field' => 'your_field_name',
  12. 'value' => 'your_filter_value',
  13. // Other params are dependant on the filter type.
  14. );
  15. }
  16. }
Programming Language: PHP