How to pull any views data to be accessible anywhere later on in Drupal 7

Last updated on 07/12/2016

Let's say you have a view and you want to get the total result items number.

The Views module provide out of the box this functionality as you can pull in the View Header or Footer:

 

Views Result Summary.

The problem with "Global: Result summary" is  that this is limiting the info placement.

If you have to get this data and place it for example in a separate block, we can do the following:

1. Statically store the Views total_items

/**
 * Implements HOOK_views_post_execute().
 *
 * Statically store total_items for further usages.
 */
function HOOK_views_post_execute($vars) {
  if (!empty($vars->query->pager->total_items)) {
    MYMODULE_store_views_total_items($vars->base_table . '__' . $vars->name . '__' . $vars->current_display, $vars->query->pager->total_items);
  }
}
 
/**
 * Registry of views total items to keep.
 *
 * @param string $view_identificator
 *   The View Display Name.
 * @param int|null $cnt
 *   The total items. If NULL, it will return the result for desired view.
 * @return mixed
 */
function MYMODULE_store_views_total_items($view_identificator, $cnt = NULL) {
  $data = &drupal_static(__FUNCTION__, []);
  // Set a new value.
  if (!empty($cnt)) {
    $data[$view_identificator] = $cnt;
  }
 
  // Otherwise return the value for specifies views display name.
  if (!empty($data[$view_identificator])) {
    return $data[$view_identificator];
  }
}
 

2. Access this data anywhere else, e.g: in a hook_block_view()

/**
 * Implements hook_block_view().
 */
function HOOK_block_view($delta = '') {
  $block = [];
 
  switch ($delta) {
    case 'my_block_name':
      $content = '';
      // Get the total items result of my view.
      $total = MYMODULE_store_views_total_items('search_api_index_main_index__search__search_main');
      if (!empty($total)) {
        $content = t('Total Found @cnt', ['@cnt' => $total]);
      }
 
      $block['content'] = $content;
      break;
  }
 
  return $block;
}

[dot]