0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WordPress の REACT での読み込み時のデバッグをするプログラム

Posted at

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 );

これで、エラーログのテキストファイルを見てデバッグしてみてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?