Drupal - How to override page title by content type

As mentioned by Ivan Jaros You can use hook_preprocess_page_title.

You just have to load the node from the route first, to get some context.

function yourtheme_preprocess_page_title(&$variables) {

  // Load the node entity from current route
  if ($node = \Drupal::routeMatch()->getParameter('node')) {

    // Load the label of the bundle
    $bundle_label = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->load($node->bundle())
      ->label();

    // Set the page title
    $variables['title'] = $bundle_label;
  }
}

If you just want to use this with certain content types, you can use $node->bundle() to get the machine-readable name and check against it.


Linus got it right for the preprocess function, but I'd personally use this to get the current node (as it's shorter and seem easier...)

$node = \Drupal::request()->attributes->get('node')

Then to access the node title, use :

$title = $node->getTitle()

or to access another custom field (with a value) :

$node->get('field_MYFIELD')->value

Actually, access everything the way you'd access these datas in a regular node preprocess function :)


Use the Metatag module it is D8-ready already and supports what you need.

Tags:

Theming

8

Hooks