Drupal - How to get contextual filter in hook_views_query_alter or hook_views_pre_execute?

The contextual filters are in $view->args.

$view->args is an array of arguments (contextual filters).

So you can do things like this:

/**
 * Implements hook_views_pre_execute().
 */
function MODULENAME_views_pre_execute(&$view) {
  // Set the first contextual filter value.
  $view->args[0] = 1;
}

Using hook_views_pre_view() may be more reliable than hook_views_pre_execute(). Based on https://www.drupal.org/node/2438623, hook_views_pre_execute() is too late in the query build processs. In contrast, https://codedrop.com.au/blog/programatically-altering-contextual-filters-views-drupal-7 provides an example of hook_views_pre_view().

For my own situation, the below code works:

/**
 * Implements hook_views_pre_view().
 */
function mymodule_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAYNAME') {
    $url = arg();
    if (isset($url[1])) {
      // YOU MIGHT HAVE TO ADJUST $url[1] TO MATCH YOUR URL ALIAS.
      if ($normal_path = drupal_get_normal_path($url[1])) {
        $path_args = explode('/', $normal_path);
      }
    }
    if (isset($path_args[1])) {
      $view->args[0] = $path_args[1];
    }
  }
}

Tags:

Views