I want to alter the limit of view using views_query_alter hook.

My code is :

function track_click_views_query_alter(&$view, &$query) {
  if($view->name == "click_list_days"){
  $w_count = count($query->where[0]['clauses']) - 1;
  $w_clause = array();
  for($i=0; $i <= $w_count; $i++) {
      $w_clause[] = "(".$query->where[0]['clauses'][$i].")";
      if($i > 0)
          unset ($query->where[0]['clauses'][$i]);
  $w_clause = implode(" AND ", $w_clause)." Group By track_click.article_title ";
  $query->where[0]['clauses'][0] = $w_clause;

How can I alter the limit of this views query? I didn't understand which query object i have to alter.

  • "which query object"? But there is only one, &$query. I don't understand what you don't know.
    – Mołot
    Jan 21, 2014 at 12:53
  • thanks for your comment. i mean, object $query->where contains the conditions added in views settings. Like that $query->limit variable is available for alter query limit? or else where i can alter the query limit in views_query_alter?
    – Cool
    Jan 21, 2014 at 12:58
  • 1
    It is usually safer to use API methods instead of changing the objects data structure directly. You can have a look at views/plugins/views_plugin_query.inc to see which methods are available.
    – berliner
    Jan 21, 2014 at 14:27
  • It works for my custom rest api views pager drupal.stackexchange.com/questions/185977/… Mar 27, 2017 at 12:35

1 Answer 1


If it's only about the number of results to return, I think you could simply implement hook_views_pre_build() and do the following:

function track_click_views_pre_build(&$view) {
  if ($view->name == 'click_list_days') {

Or inside hook_views_query_alter() you should be able to do:

  • is it not possible to do with views_query_alter? because some code is already written to alter the query based on some condition in views_query_alter. So I want to add the limit with that condition.
    – Cool
    Jan 21, 2014 at 13:01
  • I added yoiur code in views_query_alter `$view->set_items_per_page(YOUR_NUMBER_OF_RESULTS_HERE); I think it is working. Let me confirm.
    – Cool
    Jan 21, 2014 at 13:06
  • @ARUN: Yes, you should be able to do this inside hook_views_query_alter() too. I have updated the response accordingly.
    – berliner
    Jan 21, 2014 at 14:23
  • $query->set_limit(LIMIT); inside hook_views_query_alter() is not working. But $view->set_items_per_page(YOUR_NUMBER_OF_RESULTS_HERE); is working iniside hook_views_query_alter()
    – Cool
    Jan 21, 2014 at 14:31
  • $query->set_limit() is not working in hook_views_query_alter(). Is any other solutions?
    – Guru
    Jan 7, 2016 at 5:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.