wp_set_script_translations()


WordPress関数wp_set_script_translations()は、スクリプトで使用される翻訳文字列を指定したテキストドメインに関連付けるために使用されます。

構文

wp_set_script_translations( string $handle, string $domain, string $path = null );

引数の説明:

  • $handle (string) — 翻訳を関連付けるスクリプトのハンドル名。
  • $domain (string) — 翻訳のテキストドメイン。
  • $path (string) — 翻訳ファイルの絶対パス。省略可能。

例 1: 基本的な使用例

特定のスクリプトに翻訳を設定します。

wp_set_script_translations( 'my-script', 'my-text-domain' );

例 2: 翻訳ファイルのパスを指定

翻訳ファイルがカスタムディレクトリにある場合の設定。

wp_set_script_translations( 'my-script', 'my-text-domain', plugin_dir_path( __FILE__ ) . 'languages' );

例 3: プラグイン内での使用

プラグインの初期化時にスクリプト翻訳を登録。

add_action( 'init', function() {
    wp_register_script( 'my-plugin-script', plugins_url( 'script.js', __FILE__ ), array(), '1.0', true );
    wp_set_script_translations( 'my-plugin-script', 'my-plugin-domain' );
} );

例 4: 翻訳可能なスクリプトの動的設定

特定の条件下で異なるテキストドメインを設定。

if ( is_admin() ) {
    wp_set_script_translations( 'admin-script', 'admin-domain' );
} else {
    wp_set_script_translations( 'frontend-script', 'frontend-domain' );
}

例 5: 複数スクリプトへの適用

複数のスクリプトに異なるテキストドメインを設定。

wp_set_script_translations( 'script-one', 'domain-one' );
wp_set_script_translations( 'script-two', 'domain-two' );

注意事項

  • $path引数を指定しない場合、翻訳ファイルはWordPressの標準パス(wp-content/languages)に基づいて検索されます。
  • スクリプトハンドル名が正確であることを確認してください。
  • 翻訳ファイルは.json形式である必要があります。

関連機能: