説明
_n() は、数量に応じて単数形・複数形を切り替えて翻訳する関数です。
基本構文
_n( string $single, string $plural, int $number, string $domain = 'default' ): string
引数
$single:単数形$plural:複数形$number:数量$domain:テキストドメイン
戻り値
翻訳された文字列。
使い方(サンプル)
printf( _n( '%s item', '%s items', $count, 'my-theme' ), number_format_i18n( $count ) );
注意点
- 日本語は単複の区別がありませんが、他言語のためにも対応しておきます。
実務での使いどころ
- 数に応じて、単数形・複数形の文字列を、切り替えるとき(「1 件」「2 件」)。
- 翻訳できる形で、件数を表示するとき。
よくあるミスと対処
$numberを、sprintf()にも渡していない。数値が、文字列に入らない。- 単数・複数を、
ifで自分で切り替えている。翻訳ファイルで、言語ごとの規則を、使えない。 - テキストドメインを、変数にしている。
NG例
echo _n( '%d件', '%d件', $count, 'my-plugin' ); // 数値が入らない
OK例
printf(
esc_html( _n( '%s item', '%s items', $count, 'my-plugin' ) ),
number_format_i18n( $count )
);
使い分け早見表
| 関数 | 役割 |
|---|---|
_n() |
数に応じて、単数形・複数形を切り替える |
_x() |
文脈つきで、翻訳する |
number_format_i18n() |
数値を、ロケールに合わせて整形する |

コメント