Drupalwoo ☉

Custom Pathauto tokens for reliable Drupal URLs

Pathauto is a contributed Drupal module that turns content fields, titles and other values into predictable URL aliases. A pattern describes the route, while square-bracket placeholders supply changing parts such as [node:title]. This lets editors publish readable pages without manually inventing a slug for every article, service page or news item.

Custom pattern tokens extend that vocabulary when a route needs a derived, standardised or safer value. Drupal teams can expose these placeholders through the Token API, select them in the Pathauto pattern editor and reuse them across content types. The result is a URL scheme that reflects the content model rather than a collection of one-off naming conventions.

How Pathauto patterns resolve tokens

Pathauto first matches an entity against a pattern’s selection criteria, including content type and language. It then replaces each supported placeholder with a current field value and formats the result using the configured separator, case and transliteration rules. A forward slash starts a new path component, while a hyphen is the usual separator within one component.

Built-in entity tokens cover common requirements. [node:title] uses the node title, while [node:field_office] reads a field named field_office. Other tokens can expose dates, authors, taxonomy references and translated values. Availability depends on the entity type, its fields and the modules installed on the site.

A custom token should perform a specific transformation rather than duplicate a straightforward field token. Typical calculations include combining an office code with a sequence number, normalising punctuation or producing an opaque public identifier. Keeping that logic in one place prevents slightly different URL formats from appearing across separate patterns.

Planning patterns around the content model

Begin with the URL structure required by readers and search engines, then map each part to a stable source. A publication might use a content type, an office code, a reference number and a readable title. A resource library may need only a category and title, while an advice service could benefit from a concise matter code.

Australian organisations often distribute editorial teams across Sydney, Melbourne, Brisbane, Perth and Adelaide. A content model containing office values such as SYD, MEL, BNE, PER and ADL can produce useful regional paths. For example, an office field and sequence field might become MEL-0042, while a separate token could supply a generic label when an office is unknown.

Keep mutable values out of identifiers whenever possible. Titles are edited frequently, but a matter code derived from controlled fields can remain unchanged throughout the content lifecycle. If a readable title remains part of the route, decide how old aliases will be preserved and redirected after an editorial update.

Implementing a custom token safely

Place custom token code in a dedicated Drupal module rather than a theme or site-wide configuration directory. A module keeps the implementation versioned, testable and available when themes change. The following hook_token_info() implementation registers a matter code within the node token group so it can be used as [node:matter_code].

use Drupal\node\NodeInterface;

/**
 * Implements hook_token_info().
 */
function reference_desk_token_info() {
  $info['node']['tokens']['matter_code'] = [
    'name' => t('Matter code'),
    'description' => t('Office and sequence identifier used in public paths.'),
    'type' => 'string',
  ];

  return $info;
}

The replacement callback receives the entity being processed. This example expects field_office to be a plain-text field and field_sequence to contain an integer. It validates both values, removes unsupported characters from the office and applies consistent zero-padding.

/**
 * Implements hook_tokens().
 */
function reference_desk_tokens($data) {
  $node = NULL;

  if ($data instanceof NodeInterface) {
    $node = $data;
  }
  elseif (is_array($data) && isset($data['node']) && $data['node'] instanceof NodeInterface) {
    $node = $data['node'];
  }

  if (!$node || !$node->hasField('field_office') || !$node->hasField('field_sequence')) {
    return [];
  }

  $office = strtoupper(trim((string) $node->get('field_office')->value));
  $office = trim((string) preg_replace('/[^A-Z0-9]+/', '-', $office), '-');
  $sequence = (string) $node->get('field_sequence')->value;

  if ($office === '' || !preg_match('/^\d+$/', $sequence)) {
    return [];
  }

  return [
    'matter_code' => sprintf('%s-%04d', $office, (int) $sequence),
  ];
}

After enabling the module, clear Drupal’s caches so the Token API and Pathauto can discover the new definition. The token should then appear in the pattern editor under the node tokens. Required-field validation is also advisable: an empty token may produce an incomplete route when a node is saved without the expected office or sequence.

Choosing the right token source

A built-in field token is preferable when the stored value already has the required shape. Custom code adds maintenance work and creates another dependency, so it should solve a genuine formatting or privacy requirement. The following comparison shows where each approach fits.

Content requirement Built-in option Custom option Practical consideration
Readable page title [node:title] Usually unnecessary Pathauto handles punctuation and transliteration
Existing plain-text field [node:field_office] Usually unnecessary Direct field tokens are easy to maintain
Office and sequence combined Join two field tokens [node:matter_code] A custom token enforces one consistent format
Public-safe reference Use a dedicated field Derive or transform the value Internal case numbers may still need concealment

Choose a custom token when the value must be validated, abbreviated or made safe for publication. A callback can also apply business rules unavailable to ordinary field tokens. Document the expected input fields and fallback behaviour so another developer can maintain it without reverse-engineering the generated URLs.

Building and testing the pattern

In the Pathauto administration area, create a pattern for the relevant content type and add the required components. A path for an advice page could use the following structure:

/advice/[node:matter_code]/[node:title]

With the office set to Melbourne and the sequence set to 42, the editable portions might produce /advice/mel-0042/budgeting-for-volunteers. The exact case and punctuation depend on the global alias settings, so teams should agree on lowercase output, hyphen separation and transliteration before generating a large batch.

Use the token browser where possible instead of relying on typed placeholders. Test a node with a long title, ampersands, an apostrophe, an accented character and a missing optional field. Confirm that the custom token receives the correct entity and that empty values are handled deliberately rather than leaving an unusable URL component.

Save the pattern, create a test node and inspect both the generated alias and the page’s canonical URL. Existing content can be processed through Pathauto’s bulk alias update operation. Run that operation against a staging copy first, especially on a large library, because changing hundreds of routes without redirects can affect bookmarks, campaign links and indexed search results.

Handling language, privacy and edge cases

Multilingual sites need patterns that match the language context of each translation. Depending on the site’s configuration, Pathauto can create language-specific aliases or generate aliases for translated entities. Test a translated node directly, since a callback must receive the translated node when the pattern expects translated field values.

Australian publishing conventions can influence how tokens are presented. Use Australian English such as organisation and authorised, and follow conventions such as 4 July 2026 when dates appear in editorial fields. The Australian Government Style Manual is a useful reference, while Pathauto’s transliteration can turn accented characters into search-friendly forms for place names around Australia.

Aliases are public and may be indexed even when the page itself requires access. Under the Privacy Act 1988 and guidance from the Office of the Australian Information Commissioner, personal information should not be exposed in a URL without a sound basis. Avoid client names, email addresses, birth dates and sensitive case details; an apparently harmless internal sequence may still need conversion into an opaque public identifier.

Mutable titles also affect route stability. When a title changes, decide whether the alias should change with it or whether the public path should contain only the stable matter code. If aliases do change, create a redirect from the previous URL before regenerating paths. A consistent canonical path, trailing-slash policy and redirect strategy prevent duplicate URLs from competing in search results.

Deploying and maintaining tokenised paths

Treat token behaviour as part of the site’s deployment. Keep the custom module in version control, review code against Drupal and Token API updates, and deploy the Pathauto pattern through the team’s normal configuration process. Clear caches in the correct order so the token definition is registered before editors or automated operations try to use it.

Many Australian council, university, agency and not-for-profit Drupal sites manage substantial content libraries. A bulk alias update on one of these sites may consume considerable database and worker capacity. Test its duration on production-like data, schedule it outside peak publishing periods and capture the previous aliases if redirects will be required.

Monitor access logs and 404 reports after regeneration, along with search engine coverage and analytics for high-value landing pages. A token callback change can alter many routes at once, including routes that were not directly affected by the edited node. Record the field sources, formatting rules and intended fallback values so operations staff and content teams can distinguish a broken pattern from an unrelated page error.