n How To Create A Custom Token In Drupal 8 & 9 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

In this article, I'll show you how to create Token Drupal to return absolute url without language prefix.

Follow the instructions below:

Create absolute_url.info.yml file:

name: Absolute URL
type: module
description: "Returns absolute url of the site, no language prefix garanted"
package: Custom
core_version_requirement: ^8 || ^9

Create absolute_url.module file:

The first thing we’ll need in this file is, hook_tokens_info() This is where we’ll define our tokens for Drupal. Which will make your new token available in UI.

In the second half of the code, the hook_tokens() function is used to actually make the token perform its desired function.


use Drupal\Core\Render\BubbleableMetadata;

 * Implements hook_token_info()

function absolute_url_token_info()

  $info['tokens']['site']['absolute_url'] = array(
    'name' => t('Absolute URL'),
    'description' => t('Url of the site, no language prefix garanted'),

  return $info;

 * Implements hook_tokens()

function absolute_url_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata)
  $replacements = array();
  global $base_root;

  foreach ($tokens as $name => $original) {
    switch ($name) {
      case 'absolute_url':
        $replacements[$original] = $base_root;

  return $replacements;


Clear your Drupal 8 caches, and then your new token will be available in UI.

custom token in drupal 8

Next steps

  • Clear your Drupal caches. To do this I use this Drush command: drush cr if you don’t currently use Drush, I highly recommend using it, or the Drupal Console.
  • Now, go back to your site, and you should be able to see the new custom token.
  • I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.



Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook