WordPressの拡張プラグインを作っている際に、REACTで管理画面などを作っている時思った通りに動いてくれない場合があり、その場合にデバッグするコードを書いてみました。
/**
* Debugging function to log detailed information about JSON file handling.
*
* This function logs the script source, calculated hash, and checks for the existence of JSON files.
* It is intended for debugging purposes to understand how WordPress handles JSON files for translations.
*
* @since 1.0.0
*/
function wc4jp_detailed_json_debug() {
global $wp_scripts;
$handle = 'custom-script';
$text_domain = 'custom-domain';
$locale = get_locale();
if ( isset( $wp_scripts->registered[ $handle ] ) ) {
$script = $wp_scripts->registered[ $handle ];
$script_src = $script->src;
error_log( '=== JSON File Debug ===' );
error_log( 'Script src: ' . $script_src );
// WordPressがJSONファイルを探す方法を再現
$relative_src = str_replace( content_url(), '', $script_src );
$relative_src = ltrim( $relative_src, '/' );
// 複数のパターンでハッシュを計算
$patterns = array(
$relative_src,
str_replace( plugin_dir_url( __FILE__ ), '', $script_src ),
'build/index.js',
'/build/index.js',
);
foreach ( $patterns as $pattern ) {
$hash = md5( $pattern );
$json_filename = "{$text_domain}-{$locale}-{$hash}.json";
$json_path = plugin_dir_path( __FILE__ ) . "languages/{$json_filename}";
error_log( "Pattern: '{$pattern}' -> Hash: {$hash}" );
error_log( "Looking for: {$json_filename}" );
error_log( 'File exists: ' . ( file_exists( $json_path ) ? 'YES' : 'NO' ) );
if ( file_exists( $json_path ) ) {
error_log( '✓ FOUND: ' . $json_path );
$content = file_get_contents( $json_path );
error_log( 'Content preview: ' . substr( $content, 0, 200 ) );
break;
}
}
// 実際に存在するJSONファイルをリスト
$existing_files = glob( plugin_dir_path( __FILE__ ) . 'languages/*.json' );
error_log( 'Existing JSON files: ' . print_r( $existing_files, true ) );
}
}
add_action( 'admin_enqueue_scripts', 'wc4jp_detailed_json_debug', 999 );
これで、エラーログのテキストファイルを見てデバッグしてみてください。