Drupal aggregated Views: Sort by number of records AND alphabetically

Let’s say you need to have a view with the most used tags in your site. For this you would normally create a taxonomy term view, add a contextual filter for the term name, and sort by number of records so term aggregation will take place with the most used tags first.

Drupal: Aggregate by number of records in a taxonomy term view


So your view will generate the most used tags in your content. This is useful for a Tag Cloud implementation.

But what if you needed the aggregated terms to be sorted alphabetically? As you can see from the above screenshot, you can sort only in one of two ways; alphabetically or by number of records.

The following snippet takes care of this problem. Place it in a hook_prerender hook and it will sort the terms alphabetically after doing the aggregation by number of records.

* Implements hook_views_pre_render().
function MYMODULE_views_pre_render(&$view) {
  // Sort the aggregated views results alphabetically since the view won't allow it if we select to sort by .
  if ($view->name === 'view_name') {
    $taxonomy_term_data_node_name = array();
    foreach ($view->result as $key => $row) {
      $taxonomy_term_data_node_name[$key] = $row->taxonomy_term_data_node_name;
    array_multisort($taxonomy_term_data_node_name, SORT_ASC,SORT_NATURAL|SORT_FLAG_CASE, $view->result);

Obviously, you have to replace the MYMODULE with your custom module name and view_name with the machine name of your view.