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

Issue fork token-3539596

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

damienmckenna created an issue. See original summary.

damienmckenna’s picture

Temporary solution for the body field:

/**
 * 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?

damienmckenna’s picture

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

damienmckenna’s picture

Status: Active » Needs review
StatusFileSize
new2.09 KB

How about "$fieldname-wordcount"?

damienmckenna’s picture

StatusFileSize
new2.11 KB

A fixed patch, after some local testing.

damienmckenna’s picture