説明
wp_json_file_decode() は、JSONファイルを読み込み、デコードする関数です。
基本構文
wp_json_file_decode( string $filename, array $options = array() ): mixed
引数
$filename:JSONファイルのパス$options:associativeなど
戻り値
デコードした値。失敗時は null。
使い方(サンプル)
$data = wp_json_file_decode( get_theme_file_path( 'data.json' ), array( 'associative' => true ) );
注意点
- WordPress 5.9 で追加されました。
実務での使いどころ
block.jsonや設定ファイルなど、JSONファイルを、読み込むとき(WordPress 5.9以降)。
よくあるミスと対処
- 既定では、オブジェクト(
stdClass)で返る。配列が欲しいときは、associativeを指定する。 - ファイルが、存在しない、または不正なJSONのとき、
nullが返る。確認せずに使う。 - ファイルのパスを、URLで指定している。サーバー上のパスを、指定する。
NG例
$data = wp_json_file_decode( get_theme_file_uri( '/config.json' ) ); // URLではなく、パスを指定する
OK例
$data = wp_json_file_decode(
get_theme_file_path( '/config.json' ),
array( 'associative' => true )
);
if ( null === $data ) {
return;
}
使い分け早見表
| 関数 | 役割 |
|---|---|
wp_json_file_decode() |
JSONファイルを、読み込んで、デコードする |
json_decode() |
JSONの文字列を、デコードする |
wp_json_encode() |
値を、JSONの文字列にする |
関連項目
wp_json_encode()、wp_get_environment_type()
公式リファレンス:wp_json_file_decode() | Function | WordPress Developer Resources

コメント