You are here

function google_analytics_preprocess_item_list__search_results in Google Analytics 8.3

Same name and namespace in other branches
  1. 8.2 google_analytics.module \google_analytics_preprocess_item_list__search_results()
  2. 4.x google_analytics.module \google_analytics_preprocess_item_list__search_results()

Implements hook_preprocess_item_list__search_results().

Collects and adds the number of search results to the head.

File

./google_analytics.module, line 484
Drupal Module: Google Analytics.

Code

function google_analytics_preprocess_item_list__search_results(&$variables) {
  $config = \Drupal::config('google_analytics.settings');

  // Only run on search results list.
  if ($config
    ->get('track.site_search')) {

    // Get the pager manager to give us the number of items returned.

    /** @var \Drupal\Core\Pager\PagerManagerInterface $pager_manager */
    $pager_manager = \Drupal::service('pager.manager');
    $items = 0;
    if ($pager_manager
      ->getPager()) {
      $items = $pager_manager
        ->getPager()
        ->getTotalItems();
    }
    $variables['#attached']['html_head'][] = [
      [
        '#tag' => 'script',
        '#value' => 'window.google_analytics_search_results = ' . $items . ';',
        '#weight' => JS_LIBRARY - 1,
      ],
      'google_analytics_search_script',
    ];
  }
}