Add a token for word count on text fields

Created on 4 August 2025, 12 days ago

Problem/Motivation

A token for generating the word count of text fields would be useful to have.

Proposed resolution

Add a token for generating the word count of a given field.

Remaining tasks

Build a MR with the intended changes.

User interface changes

A ":wordcount" token exists for text fields.

API changes

TBD

Data model changes

TBD

✨ Feature request
Status

Active

Version

1.0

Component

User interface

Created by

πŸ‡ΊπŸ‡ΈUnited States damienmckenna NH, USA

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

  • Issue created by @damienmckenna
  • πŸ‡ΊπŸ‡ΈUnited States damienmckenna NH, USA

    Temporary solution for the body field:
    <?php
    /**
    * Implements hook_token_info().
    */
    function mymodule_token_info() {
    $info['tokens']['node']['body-wordcount'] = [
    'name' => t('Body field word count'),
    'description' => t('The word count for the body field.'),
    ];

    return $info;
    }

    /**
    * Implements hook_tokens().
    */
    function mymodule_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
    $replacements = [];

    // Node tokens.
    if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
    switch ($name) {
    case 'body-wordcount':
    if (isset($node->body->value) && !empty($node->body->value)) {
    $text = strip_tags($node->body->value);
    $replacements[$original] = str_word_count($text);
    }
    break;
    }
    }
    }

    return $replacements;
    }

    The wordcount logic itself is simple, the question is how to make a subtoken for text fields?

  • πŸ‡ΊπŸ‡ΈUnited States damienmckenna NH, USA

    The Smart Trim has some token logic that could be repurposed to handle what we need.

  • πŸ‡ΊπŸ‡ΈUnited States damienmckenna NH, USA

    How about "$fieldname-wordcount"?

  • πŸ‡ΊπŸ‡ΈUnited States damienmckenna NH, USA

    A fixed patch, after some local testing.

  • Pipeline finished with Failed
    3 days ago
    Total: 175s
    #572220
  • πŸ‡ΊπŸ‡ΈUnited States damienmckenna NH, USA

    Related: πŸ“Œ Fix tests on 8.x-1.x branch Active

  • Pipeline finished with Failed
    3 days ago
    #572339
Production build 0.71.5 2024