You are here

function matomo_preprocess_item_list__search_results in Matomo Analytics 8

Implements hook_preprocess_item_list__search_results().

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

File

./matomo.module, line 459
Drupal Module: Matomo.

Code

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

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

    // There is no search result $variable available that hold the number of
    // items found. The variable $variables['items'] has the current page items
    // only. But the pager item number can tell the number of search results.

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