load_script_translations()


WordPressのload_script_translations()関数は、スクリプトの翻訳ファイルを読み込むために使用されます。JavaScriptファイル用の翻訳データをJSON形式で読み込みます。

構文

load_script_translations( string $file, string $handle, string $domain );

引数の説明:

  • $file (string) — 翻訳ファイルのパス
  • $handle (string) — スクリプトのハンドル名
  • $domain (string) — テキストドメイン

例1: 基本的な翻訳ファイルの読み込み

スクリプトの翻訳ファイルを読み込む基本的な例です。

load_script_translations( '/path/to/translations.json', 'my-script', 'my-domain' );

例2: プラグイン内での翻訳読み込み

プラグイン内で翻訳ファイルを読み込む例です。

load_script_translations( plugin_dir_path( __FILE__ ) . 'languages/translations.json', 'plugin-script', 'my-plugin' );

例3: テーマ内での翻訳読み込み

テーマのJavaScriptファイル用に翻訳を読み込む例です。

load_script_translations( get_theme_file_path( 'languages/theme-translations.json' ), 'theme-js', 'my-theme' );

例4: 翻訳ファイルの存在チェック

翻訳ファイルが存在する場合のみ読み込む例です。

if( file_exists( '/path/to/translations.json' ) ) { load_script_translations( '/path/to/translations.json', 'check-script', 'check-domain' ); }

例5: 動的なハンドル名の使用

動的に生成したハンドル名で翻訳を読み込む例です。

$dynamic_handle = 'dynamic-script-' . time(); load_script_translations( '/path/to/dynamic.json', $dynamic_handle, 'dynamic-domain' );

例6: 複数ドメインの使用

異なるテキストドメインで複数の翻訳を読み込む例です。

load_script_translations( '/path/to/first.json', 'multi-script', 'first-domain' ); load_script_translations( '/path/to/second.json', 'multi-script', 'second-domain' );

例7: 相対パスでのファイル指定

相対パスを使用して翻訳ファイルを指定する例です。

load_script_translations( './assets/languages/relative.json', 'relative-script', 'relative-domain' );

注意点

  • 翻訳ファイルは有効なJSON形式である必要があります
  • ハンドル名はwp_register_script()wp_enqueue_script()で登録したものと一致させる必要があります
  • ファイルパスはサーバーからアクセス可能な場所を指定してください

関連機能: