From time to time we need to send messages through CiviMail that include a contact's CMS (Drupal/Wordpress/Joomla) username or ID. How can we add this to the available tokens?

1 Answer 1


Option 1: Use the CiviToken extension [recommended, CMS independent]: Fuzion's CiviToken extension provides {user.name} and {user.id} tokens by default. (Pro tip: this module also makes it easy to add custom tokens in a tokens/ folder in your CiviCRM custom PHP directory; you can duplicate and modify a file from the tokens/ folder in this extension)

Option 2: Custom token in your own Drupal module [Drupal specific]: Coleman authored a blog post some years back which outlined how to make custom tokens. The following snippet is based on that and when slipped into a custom module will make the Drupal username available as a token in CiviMail.

/* CiviCRM token addition for Drupal username */

function MYMODULE_civicrm_tokens(&$tokens) {
  $tokens['username'] = array(
    'username.drupal' => 'Drupal username',

function MYMODULE_civicrm_tokenValues(&$values, $cids, $job = null, $tokens = array(), $context = null) {
  // Username tokens
  if (!empty($tokens['username'])) {

    foreach ($cids as $cid) {
      $params = array(
        'version' => 3,
        'sequential' => 1,
        'contact_id' => $cid,
      $result = civicrm_api('UFMatch', 'get', $params);
      if (!$result['is_error']) {
        $drupalinfo = user_load($result['values'][0]['uf_id']);
        $values[$cid]['username.drupal'] = $drupalinfo->name;


Keep in mind that this is the bare bones and doesn't include any handling of a contact without a Drupal account. (So you would want to make sure to only use this token when sending to contacts with a Drupal account.)

  • nice example :)
    – Coleman
    Apr 1, 2015 at 19:15
  • 2
    Even better than avoiding non-users, you could just have an "else" that returns something innocuously generic or suggests that the recipient create an account.
    – Andie Hunt
    Apr 2, 2015 at 1:05
  • I think it's better not to produce a value if there isn't one. People can then use Smarty to provide a default value foe non-user contacts if desired.
    – Joe Murray
    Apr 2, 2015 at 23:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.