1

In my Drupal 8 site, I am using the default search page. If I enter a keyword, for example article, the search result will be listed under Search result.

I want to change that to Search result for Article (keyword).

How can I achieve this?

3
6

Here comes an example snippet on how to override the page title by URL query:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_page_title(&$variables) {

  $current_path = \Drupal::request()->getpathInfo();
  if ($current_path == '/search/node') {
    if (\Drupal::request()->query->has('keys')) {

      // Get the searched string.
      $keywords = \Drupal::request()->query->get('keys');

      // As of https://drupal.stackexchange.com/a/232304/15055 we probably
      // need to ensure the cache gets busted.
      $variables['#cache']['contexts'][] = 'url.query_args:keys';

      // Set the new title.
      $new_title = new \Drupal\Core\StringTranslation\TranslatableMarkup('Search result for Article (@keywords)', ['@keywords' => $keywords]);
      $variables['title'] = $new_title;
    }
  }
}

enter image description here

0
-1

The hook mentioned above does not work in d8.Instead you can use hook_preprocess_page(&$variables). Also you can use hook_preprocess_views_view(&$variables) and continue with the same logic . function themename_preprocess_page(&$variables) {

 $current_path = \Drupal::request()->getpathInfo();
//echo $current_path;
if ($current_path == '/search/node') {
  if (\Drupal::request()->query->has('keys')) {
    $keywords = \Drupal::request()->query->get('keys');
    echo "Search Results for " . $keywords;
    }
  }
}
1
  • Welcome to Drupal Answers! Why do you think hook_preprocess_page_title() would not work for Drupal 8? The search page isn't a view; a hook for a view would not have any effect.
    – apaderno
    Oct 27 '20 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.