Drupal 7 - How to Modify a Views Query with a Custom Module

Category: 

To make custom alterations, changes, adjustments, etc to a Views query in Drupal 7, try this module (or add the code in the .module and .view.inc files to your own custom module):

my_module.info

name = My Module
description = Behold my awesome module.
core = 7.x
package = Other

my_module.module

<?php

/**
 * Implements hook_views_api().
 */
function my_module_views_api() {
  return array(
    'api' => 3, 
    'path' => drupal_get_path('module', 'my_module'), 
    'template path' => drupal_get_path('module', 'my_module'),
  );
}

my_module.views.inc

<?php

/**
 * Implements hook_views_query_alter().
 */
function my_module_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view_machine_name' && $view->current_display == 'page') {
    drupal_set_message("I can make changes to the view here..");  
  }
}

From here, I'll typically use the Devel module's dpm function to investigate the $view and $query objects and make the necessary programmatic changes.

Be sure you use the correct machine name for the view's display. In the example above, the machine name for the Page display of my view was 'page', so in the boolean I use:

$view->current_display == 'page'

To retrieve your view's display name machine name, click on your view's display button when editing your view, then check out the URL in your address bar, it will be something like this:

admin/structure/views/view/my_view_machine_name/edit/page

In the above example, the Page display's machine name was 'page' on the view. Other examples of display machine names are: default, page_1, attachment_1, etc