ワードプレスの_n関数の使用方法・解説

概要

_n 関数は、特定の文言の翻訳において、数値に基づいて異なるテキストを返すために使用される関数です。この関数は、主に次のような機能を実装する際に利用されます:

  1. アイテムの個数に応じて異なるメッセージを表示する
  2. フォームやメニューのオプション数に基づくテキストの表示
  3. プラグインやテーマの管理画面での項目数表示
  4. 投稿やコメントのカウントに基づくメッセージ表示
  5. 商品の在庫やカート情報の動的表示
  6. 関連するコンテンツ数に基づいたテキストの表示
  7. 記事のタグやカテゴリ数に応じた表示文の変更
  8. ユーザーからのフィードバックや評価に基づいたメッセージのカスタマイズ

構文

_n( $singular, $plural, $number, $domain );

パラメータ

  • $singular (string) – 数量が1つのときに表示するテキスト。
  • $plural (string) – 数量がそれ以外のときに表示するテキスト。
  • $number (int) – 表示する数値。
  • $domain (string) – テキストドメイン、ローカライズに使用。

戻り値

  • string – 数量に応じた適切なテキストを返します。

関連する関数

使用可能なバージョン

  • 2.1.0 以降のバージョンで使用可能。

コアファイルのパス

  • wp-includes/l10n.php

この関数のアクションでの使用可能性

アクション 使用例
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

非推奨または削除されたバージョン

  • 現在のところ、_n 関数は特定のバージョンで非推奨または削除されていません。

サンプルコード

  1. 商品の在庫数表示

    $stock_count = 5;
    echo sprintf( _n( '%d item in stock', '%d items in stock', $stock_count, 'text-domain' ), $stock_count );
    

    このコードは、在庫が1つの場合には「1 item in stock」を、2つ以上の場合には「5 items in stock」というメッセージを表示します。
    引用元: https://www.sitepoint.com/wordpress-internationalization/

  2. コメント数の表示

    $comments_count = 1;
    echo sprintf( _n( 'One comment', '%d comments', $comments_count, 'text-domain' ), $comments_count );
    

    ここでは、コメントが1件の場合には「One comment」を、2件以上の場合には「2 comments」を表示します。
    引用元: https://developer.wordpress.org/reference/functions/_n/

  3. ブログの投稿数に応じた表示

    $post_count = 10;
    echo sprintf( _n( 'You have published one post', 'You have published %d posts', $post_count, 'text-domain' ), $post_count );
    

    投稿数に応じてメッセージを変え、1件なら「You have published one post」、それ以外なら「You have published 10 posts」というメッセージを表示します。
    引用元: https://wpbuffs.com/wordpress-internationalization/

  4. ユーザーのメッセージ

    $message_count = 0;
    echo sprintf( _n( 'You have one message', 'You have %d messages', $message_count, 'text-domain' ), $message_count );
    

    メッセージの個数に応じて表示を制御し、1件なら「You have one message」、0件の時は何も表示しません。
    引用元: https://torquemag.io/2019/02/wordpress-translation-functions/

  5. タグ数の表示

    $tag_count = 3;
    echo sprintf( _n( 'You have one tag', 'You have %d tags', $tag_count, 'text-domain' ), $tag_count );
    

    タグの数に合わせてメッセージを変える処理で、1件の時は「You have one tag」、2件以上なら「You have 3 tags」と表示します。
    引用元: https://www.tutorialrepublic.com/faq/how-to-get-wordpress-post-tag-count.php

この関数について質問する


上の計算式の答えを入力してください