Skip to main content
3 of 3
added 362 characters in body
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.)

I.e. I want it to be 'Add X' for any 'X' when it originally was 'Create X'. For example: 'Create article' should become 'Add article'. And if the title is 'Bar Article', I should be left as is.

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().
 */

First attempt:

function mytheme_preprocess_page_title(&$variables) {
  $request     = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title       = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
}

Second attempt, based upon suggestion by 4k4:

function mytheme_preprocess_page_title(&$variables) {
  $title = $variables['title'];
  if ($title instanceof TranslatableMarkup) {
    $title = $title->getUntranslatedString();
    $title = str_replace('Create', 'Add', $title);
    $variables['title'] = t($title);
  }
  else {
    $variables['title'] = Markup::create(str_replace('Create', 'Add', $title));
  }  
}

The titles I want to change come from Drupal core and they are translatable, so its the instanceof TranslatableMarkup branch that gets executed, but I agree with having a fallback in case they're not, is a good idea.

However, while a good start, this is not a complete solution. It changes the rendered title of the add article form from "Create article" to "Add @name".

enter image description here

I've upvoted the answer by 4k4, as it goes much further towards a solution than my first attempt, but it is still not complete.

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