Create your own tokens

Public

Source: http://fredparke.com/blog/create-your-own-tokens-drupal-7
hook_token_info(), is used to declare any custom tokens.

Get raw version
php
  1. /**
  2.  * Implements hook_token_info().
  3.  */
  4. function module_name_token_info() {
  5. $info = array();
  6. // Define a new token type.
  7. $info['types']['my_custom_tokens'] = array(
  8. 'name' => t('My custom tokens'),
  9. 'description' => t('A token type for my custom tokens.'),
  10. );
  11. // Define any new tokens.
  12. $info['tokens']['my_custom_tokens']['my_cool_token'] = array(
  13. 'name' => t('My cool token'),
  14. 'description' => t('A token I use to show that I am cool.'),
  15. );
  16. return $info;
  17. }

Define token content with hook_tokens().

Get raw version
php
  1. /**
  2.  * Implements hook_tokens().
  3.  */
  4. function module_name_tokens($type, $tokens, array $data = array(), array $options = array()) {
  5. $replacements = array();
  6.  
  7. if ($type == 'my_custom_tokens') {
  8. // Loop through the available tokens.
  9. foreach ($tokens as $name => $original) {
  10. // Find our custom tokens by name.
  11. switch ($name) {
  12. case 'my_cool_token':
  13. // Work out the value of our token.
  14. $value = 'Whatever we want the token to be';
  15. // Give our token it's value!
  16. $replacements[$original] = $value;
  17. break;
  18. }
  19. }
  20. }
  21.  
  22. return $replacements;
  23. }