Skip to content
All posts
WordPress2 min read

How I Structure React-Based WordPress Plugins

A React-based WordPress plugin is really two projects in one folder: the PHP that WordPress loads and the React code that gets compiled. Here’s the simple folder structure I use to keep them organized, plus what to do when src/ is already taken.

On this page
  1. The idea
  2. The structure
  3. What if `src/` is already taken?
  4. Shipping it
  5. Wrapping up

How I Structure React-Based WordPress Plugins

The first time I built a WordPress plugin with React, the code worked. The folder was a mess. PHP files, JSX, build output and config all sat side by side, and a month later I couldn't find a thing.

I've since settled on a simple layout that I reuse for every plugin. Here it is.

The idea

A React plugin is really two projects sharing one folder. One is the PHP that WordPress loads. The other is your React code, which gets compiled into a build/ folder. WordPress never reads your React source directly; it only loads what's in build/.

To handle the build, I use @wordpress/scripts. It's the official tool, it works with almost no setup, and it leaves React and other WordPress packages out of your bundle, since WordPress already loads them.

The structure

my-plugin/
├── my-plugin.php        # Plugin header + bootstrap
├── package.json
├── webpack.config.js    # Optional: extra entry points
├── includes/            # PHP classes
│   ├── class-admin.php
│   └── class-rest-api.php
├── src/                 # React source
│   ├── admin/
│   │   ├── index.js
│   │   ├── App.js
│   │   └── components/
│   └── blocks/
│       └── my-block/
└── build/               # Compiled output (this is what ships)

PHP lives in includes/, React lives in src/, and compiled files land in build/. Each folder has one job, so you always know where to look.

What if src/ is already taken?

If you use Composer, your PHP classes probably live in src/ already. That's fine. Just give React its own folder instead. I use app/:

my-plugin/
├── src/     # PHP
├── app/     # React
└── build/

Then tell the build tool where to find it:

"scripts": {
  "start": "wp-scripts start --webpack-src-dir=app",
  "build": "wp-scripts build --webpack-src-dir=app"
}

If you have a custom webpack.config.js, point its entries at app/ as well. Everything else stays the same, because PHP still loads from build/.

Shipping it

When you release, include your PHP files and the build/ folder. Leave out node_modules/ and your React source.

One warning if you went the app/ route: src/ is your PHP now, so don't exclude it out of habit. I did that once and shipped a plugin with no PHP classes. It wasn't a good day.

Wrapping up

PHP in one place, React in another, compiled code in build/. It's not fancy, but it keeps everything easy to find, and that's the whole point.

Want a head start? Run npx @wordpress/create-block my-plugin and it'll scaffold most of this for you.