Here’s a step-by-step guide:

1. Build Your React Application

Run the following command in your React project directory:

bashCopy codenpm run build

This generates a build folder with static files, including a manifest.json (or similar file like asset-manifest.json).

2. Copy Build Files to WordPress Theme

Copy the entire build folder to a suitable location within your WordPress theme, such as wp-content/themes/your-theme/react-build.

3. Read and Enqueue Files in functions.php

Add the following code to your theme’s functions.php file to read the manifest and enqueue the necessary files:

phpCopy codefunction enqueue_react_app() {
    $react_build_dir = get_template_directory() . '/react-build';
    $react_build_uri = get_template_directory_uri() . '/react-build';

    // Read the manifest file
    $manifest_path = $react_build_dir . '/asset-manifest.json';
    if (file_exists($manifest_path)) {
        $manifest = json_decode(file_get_contents($manifest_path), true);

        // Enqueue the main CSS file
        if (isset($manifest['files']['main.css'])) {
            wp_enqueue_style('react-app', $react_build_uri . $manifest['files']['main.css'], array(), null);

        // Enqueue the main JS file
        if (isset($manifest['files']['main.js'])) {
            wp_enqueue_script('react-app', $react_build_uri . $manifest['files']['main.js'], array(), null, true);

        // Enqueue any additional JS chunks (optional)
        if (isset($manifest['entrypoints'])) {
            foreach ($manifest['entrypoints'] as $file) {
                if (preg_match('/\.js$/', $file)) {
                    wp_enqueue_script('react-chunk-' . md5($file), $react_build_uri . $file, array(), null, true);
add_action('wp_enqueue_scripts', 'enqueue_react_app');

4. Modify header.php and footer.php

Ensure your header.php includes the root div for the React app:

phpCopy code<!DOCTYPE html>
<html <?php language_attributes(); ?>>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); ?>
<body <?php body_class(); ?>>
    <div id="root"></div>
    <?php wp_footer(); ?>

Make sure your footer.php includes the wp_footer() function call:

phpCopy code<?php wp_footer(); ?>

5. Run Your WordPress Site

After completing these steps, your React app should be properly integrated into your WordPress site, with assets being dynamically referenced based on the manifest file.


This approach handles the hashed filenames generated by the React build process by reading the asset-manifest.json file and dynamically enqueuing the appropriate assets in your WordPress theme. This ensures that the correct files are loaded and avoids cache issues.

By Minart

Leave a Reply

Your email address will not be published. Required fields are marked *