Error message

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.

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


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 files to your own custom module):

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



 * 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'),


 * 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:


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


For some reason I couldn't get Drupal to execute the hook_views_query_alter until I put it the function directly in my .module file.

tyler's picture

Thanks for pointing that out Dan. It's possible Views is expecting it in the .module file, since this article was posted. I'll definitely keep that in mind next time I utilize this technique and will update the article accordingly. Michigan Drupal!

tyler's picture

Just to confirm, I had to use the approach documented in this article, and it worked fine.

For others, Dan did follow up and say: "It magically started working after I deleted the include file and created a new one. Can't confirm but I probably named the first file because the file that now works is correctly named"

Add new comment