Custom header token in Drupal 8
In one of the articles earlier we already mentioned a custom module for custom tokens in Drupal 8/9, today we will add a custom node header token from the content field.
Add a custom title field to the content. After that, we go to the file of our module grabovski_token.tokens.inc and add the code to the function
function grabovski_token_token_info() {
$node['custom_node_title'] = [
'name' => t('Custom node title'),
'description' => t('Custom node meta title'),
];
And below, in the same function, in the return add
'node' => $node,
In the same file, but below, in the function
function grabovski_token_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
after line
$replacements = [];
Add the following code
if ($type == 'node' && !empty($data['node'])) {
$current_path = \Drupal::service('path.current')->getPath();
$path_args = explode('/', $current_path);
$node = \Drupal::entityTypeManager()->getStorage('node')->load($path_args[2]);
foreach ($tokens as $name => $original) {
switch ($name) {
case 'custom_node_title':
if (!$node->field_custom_title->isEmpty()){
$replacements[$original] = $node->field_custom_title->getString();
}else{
$replacements[$original] = $node->label();
}
break;
}
}
}
First, there is a check for the type of material - a node, then it is checked whether the field of the custom title is empty - field_custom_title, in the case if it is not empty - its value is displayed, if it is empty - we display the usual title of the node.