A feature I regularly use in WordPress development are shortcodes. I needed the same functionality in Drupal. Like most things I’ve found with Drupal, it’s not as easy or clear on how to go about it. No need to fret though, I’ll walk you through how to get ahead of the learning curve and easily create custom tokens.
Drupal’s documentation — or lack of — and a lot of posts I found on how to create tokens had conflicting information. This was mainly due to portions of the Token module getting moved into the core beginning with D7. Though, it doesn’t due much good for typical users if there’s no interface or UI for defining custom tokens.
In the examples below, I’ll show you how to easily create custom tokens within a module.
Creating Custom Tokens in Drupal 7
To create custom tokens in D7, we’re going to use two hooks:
hook_token_info()– This is where you’ll create the token and define what they are.
hook_tokens()– This is where the magic happens, you’ll tell Drupal what to replace your tokens with.
Below, we’re going to create a custom token that holds the user’s session status (Logged In, Logged Out). You could use this token in conjunction with GA’s custom dimensions to gather more detailed analytics.
Step 1: Create & define the custom token.
In your module, add the following code:
The code above will return an associative array with your custom tokens data:
- Name: The translated human-readable short name of the token.
- Description: A translated longer description of the token.
It’s important to note the structure of the array:
$info['tokens']['user']['session-status']. Where user is the token type, and session-status is the machine-friendly name.
Step 2: Replace the token.
In your module, after the code above, add the following:
That’s it! The session status token should now be available and appear in the list of tokens wherever tokens are available.