Setting up a local development environment for a PHP project is often harder than it should be.
You could setup a local PHP and database server or do the same in a virtual machine.
But the most common way nowadays is using Docker containers for that.
The team behind the Gutenberg editor recently released the @wordpress/env
package which provides npm
scripts to setup and run WordPress in Docker containers.
The benefit when using this package is that it hides all Docker related commands behind an npm run
call which means that you don't need to learn those too.
Setup project
To begin with you need to install the @wordpress/env
npm package by running the following command in your project folder:
npm install @wordpress/env --save-dev
Now add this npm script to your package.json
file:
// package.json
"scripts": {
"wp-env": "wp-env"
}
Additionally you need to configure the environment by adding a .wp-env.json
file in your project root and adjust it to your needs (see the Block Editor Handbook for reference):
// .wp-env.json
{
"core": "WordPress/WordPress",
"plugins": [ "." ]
}
Install and start WordPress
You can now run the following command to setup and run the local environment (You need to have Docker installed before running this command):
npm run wp-env start
This will setup a local WordPress installation and mounts the current project folder into the plugins
directory of the WordPress installation (as configured in the .wp-env.json
file) so that you can test it as you are developing it.
After this command has completed your local WordPress environment should be running behind the port 8888
and is accessible by opening:
- Frontend: http://localhost:8888/
- Backend: http://localhost:8888/wp-admin (Username:
admin
/ Password:password
)
Stopping the environment
Since Docker uses a lot of your machines resources you should stop the environment when you're done using it. You can do that by running the following command:
npm run wp-env stop
There are also some other commands (eg. for cleaning the database) which are documented here: https://developer.wordpress.org/block-editor/packages/packages-env/#command-reference