Limit records displayed in a view using hook_views_query_alter on a Drupal 6 website

Submitted by ionut on 13/05/2011

Tags 

drupal, views, query, hook

Probably at some time you will need to modify some view's output by code...

So, here's how you can for example limit the output to a certain number of records...

1. Implement a hook_views_query_alter in your custom module

function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
}

2. As you probably realized, there are 2 objects available that can be altered: $view and $query.

The view class is defined in [path_to_modules_folder]/modules/views/includes/view.inc
and the views_query class is defined in [path_to_modules_folder]/modules/views/includes/query.inc - Open them and see what properties and methods are available.

Let's limit the output to 2 records with

$view->set_items_per_page(2);

and also let's hide the pager

 

$view->set_use_pager(FALSE);

Complete example:

function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
$view->set_items_per_page(2);
$view->set_use_pager(FALSE);
}

That's it!

Happy coding

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.