Creation of custom tokens / placeholder for Drupal 7. I searched many forums to get any help regarding the creation of custom tokens but I failed in getting a proper solution that's why I decided to post this topic to help drupal users. For creating custom token we will use three token api function.

hook_token_info
hook_tokens($type, $tokens, array $data = array(), array $options = array())
token_replace($text, array $data = array(), array $options = array())

/**
 * Implements hook_token_info(). This hook will register tow token lname and fname.
 */
function myhook_token_info() {
  $info['tokens']['custom']['fname'] = array(
    'name' => t('First name'),
    'description' => t('First name re placer for fname '),
  );
  $info['tokens']['custom']['lname'] = array(
    'name' => t('Last name'),
    'description' => t('Last name re placer for lname '),
  );
  return $info;
}

/**
 * Implements hook_tokens(). This hook will operate the token and replace it with it's value.
 */
function myhook_tokens($type, $tokens, array $data = array(), array $options = array()) {
	$replacements = array();
	$sanitize = !empty($options['sanitize']);
	if ($type == 'custom') {
	    foreach ($tokens as $name => $original) {
	      	if (array_key_exists($name, $data)) {
	      		$replacements[$original] = $data[$name];	
	      	}
	    }
	}
	return $replacements;
}

/**
 * Here we will use the token_replace() function to get the actual content after replacement.
 */
function myhook_myfunction() {
	$custom = array();
	$custom['fname'] = 'Rajat';
	$custom['lname'] = 'Gusain';
	$data = $custom;
	$temp = "Full name : [custom:fname] [custom:lname]";
	$temp = token_replace($temp, $data);
// After token replacement $temp variable will contain " Full name : Rajat Gusain"
}

Any comment, compliment, problem is welcome.

Comments

fleshgrinder’s picture

What I came up with, fully documented.

/**
 * @file
 * Provides special token to use with pathauto.
 *
 * @see httx://drupal.org/node/1308488
 */

/**
 * Provide information about our custom placeholder/token.
 *
 * @see httx://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_token_info/7
 * @see httx://api.lullabot.com/token_example_token_info/7
 * @return array
 *   An associative array of available tokens and token types.
 */
function MODULE_NAME_token_info() {
	$info['tokens']['node']['pathauto'] = array(
		'name' => t('Pathauto'),
		'description' => t('Title ready for use with pathauto.'),
	);
	return $info;
}

/**
 * Provide replacement values for placeholder tokens.
 *
 * @see httx://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_tokens/7
 * @see httx://api.lullabot.com/token_example_tokens/7
 * @param string $type
 *   The machine-readable name of the type (group) of token being replaced, such
 *   as 'node', 'user', or another type defined by a hook_token_info()
 *   implementation.
 * @param array $tokens
 *   An array of tokens to be replaced. The keys are the machine-readable token
 *   names, and the values are the raw [type:token] strings that appeared in the
 *   original text.
 * @param array $data (optional)
 *   An associative array of data objects to be used when generating replacement
 *   values, as supplied in the $data parameter to token_replace().
 * @param array $options (optional)
 *   An associative array of options for token replacement; see token_replace()
 *   for possible values.
 * @return array
 *   An associative array of replacement values, keyed by the raw [type:token]
 *   strings from the original text.
 */
function MODULE_NAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
	$replacements = array();
	$sanitize = !empty($options['sanitize']);

	if ($type == 'node' && !empty($data['node'])) {
		$node = $data['node'];

		foreach ($tokens as $name => $original) {
			switch ($name) {
				case 'pathauto':
					$replacements[$original] = str_replace(
							array('&', '&'),
							'and',
							$sanitize ? filter_xss($node->title) : $node->title
					);
					break;
			}
		}
	}

	return $replacements;
}

PS: Had to replace http:// with httx:// because otherwise the text formatting would fuck the code up.

et0r’s picture

I've been looking for a reference like this for hours! Thanks!

aendra’s picture

This is great.

Thanks so much for posting that! Saved me a tonne of time, and the inline documentation is fantastic.

Ændrew Rininsland
News Developer and polynerd
http://www.aendrew.com

DrCord’s picture

This example doesn't seem to work with Drupal 7. I ended up using the Examples for Developers module and the token_example sub module to get a good template to start from.

frob’s picture

Just in case anyone wanted a version without tabs and instead used spaces. Here:

/**
 * @file
 * Provides special token to use with pathauto.
 *
 * @see httx://drupal.org/node/1308488
 */

/**
 * Provide information about our custom placeholder/token.
 *
 * @see httx://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_token_info/7
 * @see httx://api.lullabot.com/token_example_token_info/7
 * @return array
 *   An associative array of available tokens and token types.
 */
function MODULE_NAME_token_info() {
  $info['tokens']['node']['pathauto'] = array(
    'name' => t('Pathauto'),
    'description' => t('Title ready for use with pathauto.'),
  );
  return $info;
}

/**
 * Provide replacement values for placeholder tokens.
 *
 * @see httx://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_tokens/7
 * @see httx://api.lullabot.com/token_example_tokens/7
 * @param string $type
 *   The machine-readable name of the type (group) of token being replaced, such
 *   as 'node', 'user', or another type defined by a hook_token_info()
 *   implementation.
 * @param array $tokens
 *   An array of tokens to be replaced. The keys are the machine-readable token
 *   names, and the values are the raw [type:token] strings that appeared in the
 *   original text.
 * @param array $data (optional)
 *   An associative array of data objects to be used when generating replacement
 *   values, as supplied in the $data parameter to token_replace().
 * @param array $options (optional)
 *   An associative array of options for token replacement; see token_replace()
 *   for possible values.
 * @return array
 *   An associative array of replacement values, keyed by the raw [type:token]
 *   strings from the original text.
 */
function MODULE_NAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'pathauto':
          $replacements[$original] = str_replace(
            array('&', '&'),
            'and',
            $sanitize ? filter_xss($node->title) : $node->title
          );
          break;
      }
    }
  }

  return $replacements;
nicknickoli’s picture

Very helpful, thanks.

betoaveiga’s picture

Thanks for the info, it's very useful.
I also recommend this link that has a more practical approach:
http://blog.artemshymko.com/how-create-custom-token-drupal-7

Senior Drupal Developer — Backend, Frontend & DevOps/CI/CD

kevla’s picture

I'm getting a WSOD for that link

cigotete’s picture

a white page is a very practical approach ;-)

rajatgusain’s picture

Really a white page :(

hargobind’s picture

priceh’s picture

Is there a way to create a custom token using tokens that already exist? I'd like to be able to make these pipes only appear if there is data in the next token.
[node:title] | [example:field] | [token:another]

Maybe I'm missing something, but I seriously can not figure it out.

jaypan’s picture

I'm guessing that there probably isn't a way to do this. Tokens are simply done with a search and replace, there is no logic used in their processing.

Contact me to contract me for D7 -> D10/11 migrations.

maindeepak’s picture

Very helpful, thanks.

jon_stewart’s picture

Thanks for taking the trouble to write that. Made my life a lot easier! :-)
Jon

Jon