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

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