
【Gutenberg】ブロックエディタに文字数カウントを常時表示する
ブロックエディタに任意の要素を追加する方法を使用することで、文字数カウントを常時表示させておくことが可能です。
文字数カウントコンポーネント作成
Word Count パッケージを使用して文字数カウント用のコンポーネントを作成します。
count 関数は第一引数にカウント対象の文字列、第二引数にカウントタイプを指定します。
カウントタイプは3種類あります。
- words (単語数(英語など単語の前後に空白があるような言語用))
- characters_excluding_spaces (スペースを除いた文字数)
- characters_including_spaces (スペースを含んだ文字数)
日本語でデフォルトで使用されているのは characters_including_spaces です。

getEditedPostAttribute( 'content' ) で編集中の本文を取得し、カウントタイプ characters_including_spaces で文字数をカウントするコンポーネントを作成します。
components/word-count.js
const { withSelect } = wp.data;
const { compose } = wp.compose;
const { count } = wp.wordcount;
const { sprintf } = wp.i18n;
const getWordCount = ( content ) => count( content, 'characters_including_spaces' );
const WordCount = ( { content} ) => <span>{ sprintf( translate( '%d characters' ), getWordCount( content ) ) } </span>;
export default compose(
withSelect( select => ( {
content: select( 'core/editor' ).getEditedPostAttribute( 'content' )
} ) ),
)( WordCount );
コンポーネントを render
作成した文字数カウントコンポーネントをブロックエディタに表示させます。
ヘッダーあたりが見やすいと思うので、 .edit-post-header-toolbar に挿入させます。
index.js
const { render } = wp.element;
import { WordCount } from './components';
wp.domReady( function() {
document.querySelector( '.edit-post-header-toolbar' ).insertAdjacentHTML( 'beforeend', '<div class="character-count"></div>' );
render(
<WordCount/>,
document.querySelector( '.character-count' ),
);
} );
読み込み
後はコンパイルして wp_enqueue_script で依存関係を指定しながら読みこめば完成です。
動作

プラグイン化
導入手順
- 最新版をGitHubからダウンロード
release.zip - 「プラグインのアップロード」からインストール
- プラグインを有効化


GitHub Actions のリリース手順を自動化する GitHub Actions
GitHub Actions で作業を効率化

