Make WordPress Core

Opened 2 months ago

Last modified 4 weeks ago

#57987 new enhancement

Introduce new `wp_word_count` function

Reported by: wildworks's profile wildworks Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Editor Keywords: has-patch has-unit-tests
Focuses: Cc:

Description

In the WordPress core, there is a JavaScript-based WordCounter(https://core.trac.wordpress.org/browser/trunk/src/js/_enqueues/wp/utils/word-count.js) class to count the number of characters appropriately based on language type. My understanding is that this logic is incorporated into the @wordpress/wordcount(https://github.com/WordPress/gutenberg/tree/trunk/packages/wordcount) package in Gutenberg. This utility is used in the document panel of the block editor to calculate the number of characters.

Also, in Gutenberg PR(https://github.com/WordPress/gutenberg/pull/43403), a new "Post Time To Read" block was added. This block shows minutes required to finish reading the post. This block uses the wordcount package to calculate the number of characters in the content from which the time is calculated. However, the exact same PHP-based logic was needed to render this block server-side on the front-end side. Therefore, we added a new wp_word_count() PHP function at the same time we added this block.

Since this block is experimental, the block and this function will not be bundled into the core. However, given the possibility that this block may become less experimental and be incorporated into the core in the future, and given the recent addition of the wp_get_word_count_type() function, we may consider implementing this function in the core.

This PHP function is a direct transfer of the logic of the JavaScript-based WordCounter.count. Unit tests have also been implemented.
https://github.com/WordPress/gutenberg/pull/43403/files#diff-796959a4b78efdd6a2af2ec364be6a4af2566a57041673f2fabbd153bc743cf9

Change History (3)

#1 @sabernhardt
5 weeks ago

  • Component changed from General to Editor

This ticket was mentioned in PR #4430 on WordPress/wordpress-develop by @wildworks.


4 weeks ago
#2

  • Keywords has-patch has-unit-tests added

#3 @wildworks
4 weeks ago

I have attached the patch. This patch includes the function itself and unit tests.

The unit test is based on this Qunit test. The test cases and expected results are exactly the same as for QUnit.:
https://github.com/WordPress/wordpress-develop/blob/24c4d56d517adca38a51ef8ea03bd9886cf6f2d6/tests/qunit/wp-admin/js/word-count.js

The function is based on this JS file. While there are differences in the way regular expressions are written due to language, I believe the logic is the same.: https://github.com/WordPress/wordpress-develop/blob/24c4d56d517adca38a51ef8ea03bd9886cf6f2d6/src/js/_enqueues/wp/utils/word-count.js

If there is anything I am missing, please let me know.

Note: See TracTickets for help on using tickets.