Skip to main content
1 of 3
Free Radical
  • 15.1k
  • 9
  • 48
  • 83

How to alter page title "Create X" to "Add X" for all X?

In Drupal 7, there was drupal_get_title()and drupal_set_title(). They're history.

I want to alter the page title "Create X" to "Add X" for all X, and I think hook_preprocess_page_title() in my .theme-file is the right place to do it. (If you disagree, please say so.)

Basically, I want to sniff the title string and if it starts with 'Create ', alter it to 'Add '. This is so far I've gotten, and this is obviously incomplete:

/**
 * Implements hook_preprocess_page_title().
 */
function guidedtheme_preprocess_page_title(&$variables) {
  $request     = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title       = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
}

Problems:

  1. $title is not a string. The string is somewhere in there, but how do I extract it to see what it starts with?
  2. How do I actually change it in the context of a preprocess hook. I.e. what is equivalent of drupal_set_title() in this context?

I don't want to use the String Overrides module for this for several reasons, mostly because this theme should work across translations without requiring extra configuration when deployed.

Free Radical
  • 15.1k
  • 9
  • 48
  • 83