I need a getter for the number of search results. The workaround I used in past was wonky from first day as taking the number of search results from a global pager variable is really not the cleanest code...

/**
 * Implements hook_preprocess_search_results().
 *
 * Collects and adds the number of search results to the head.
 */
function google_analytics_preprocess_search_results(&$variables) {
  // There is no search result $variable available that hold the number of items
  // found. But the pager item mumber can tell the number of search results.
  global $pager_total_items;

  $page['#attached']['js'][] = array(
    'data' => 'window.googleanalytics_search_results = ' . intval($pager_total_items[0]) . ';',
    'type' => 'inline',
    'group' => JS_LIBRARY-1,
  );
  drupal_render($page);
}

Can you share how I'm able to get the number in hook_page_alter(), please?

Something like SearchResult::getNumberOfItems would be great. Other search modules should be able to reuse this so I'm able to get this from all modules the same way without adding special handling for every module.

Comments

hass’s picture

Issue summary: View changes

a

hass’s picture

Issue summary: View changes

a

jhodgdon’s picture

Status: Active » Fixed

You might look at the pager functions and theme templates in D8 for a clue:
https://api.drupal.org/api/drupal/core!includes!pager.inc/function/pager...
https://api.drupal.org/api/drupal/core!modules!system!templates!pager.ht...

It looks like the global variables are still the same.

The alternative would be to look at the search query, but you could not do that in a hook_page_alter().

hass’s picture

Status: Fixed » Active

That is too static. We need a flexible solution that works with every search module.

#2114985: How to grab the keywords of a search? has the same inflexibility. That is all bad design. We should write a service or getter/setter to allow every module to reuse this API.

jhodgdon’s picture

Status: Active » Postponed (maintainer needs more info)

I am not sure how this would work, what problem you are trying to solve, what you'd like this general API to look like, or how you propose to have access to it as late as hook_page_alter().

But if you can illustrate what you are hoping for in a patch, the search module maintainers (of which I am one) will certainly review it. Perhaps start with a real issue summary that explains what you need an how you propose to solve it?

jhodgdon’s picture

Status: Postponed (maintainer needs more info) » Closed (duplicate)

Actually, this is a duplicate of
#22627: Showing result count and result range in search results
which is the oldest issue in the search.module queue.

jhodgdon’s picture

Issue summary: View changes

a