How to create custom token in Drupal 8

In Drupal 8 custom token can be created in following way :

It is good practice to write code related to tokens in tokens.inc file. Include the tokens.inc file in your module in following way.

module_load_include('inc', 'custom_module', 'custom_module.tokens');

Now in your custom_module.tokens.inc file, extend the hooks => hook_tokens_token_info and hook_tokens in this way.

/** * Implements hook_token_info(). */
function custom_module_token_info()
{ $info = []; $info['tokens']['custom_module']['node_body_summary'][] = 'A token to extract desired characters from
Node body to be used in meta descriptions';
return $info;
}
/** * Implements hook_tokens(). */
function custom_module_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata)
{ $replacements = []; if ($type == 'custom_module_token') { foreach ($tokens as $name => $original) { switch ($name) { case 'node_body_summary': $replacements[$original] = = 'My Custom Token'; break; } } }
return $replacements;
}

 

Now you can use this token like this : [custom_module:node_body_summary];