All about counting Views results

Wed, 2011-12-28 08:16

Here's a quick tutorial about counting Views (Views 2/3, Drupal 6/7) results elesewhere from your site. We load the View, set pager to unlimited (because we need to count all items that return to the View) and then execute the View.

Displaying stuff is really easy with Views and here's how to count them and extend the power of Views.

<?php
// Here we load the View that has machine name "my_view_name".
$view = views_get_view('my_view_name');
// Set the display. Omit to use defaults.
$view->set_display('page_5');
// Optionally set arguments. remove the line if no arguments need to be pushed.
$view->set_arguments( array( 1, 2, 3 ) );
// We reset pager to 0, that means we need to return all items to the View. views_get_view sets pager to 10 somehow if the default setting is 10.
$view->pager['items_per_page'] = 0;
// Executing view
$view->execute();
// Here's the real counting
$count = count($view->result);
// Optionally print $count.
print $count;
?>

Setting arguments is handy but if you don't want it, just remove the line. array(1 ,2 ,3) is just for an example. You can use arguments from $user, $node(if loaded) or URL arguments.
Ex: to push current node ID,
$view->set_arguments( array( arg(1) ) ); -- Make sure arg(1) is numeric.

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $view=views_get_view.....

Update in May 31, 2012

Thanks to Zoltan for this tip about using $view->total_rows to get the total row count instead of count($view->result).
I'd suggest trying $view->total_rows first if it gives accurate results. I had to manually set the pager value to 0 to avoid Views giving 10, or any other items-per-page value as the total number of rows though.