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 released the @wordpress/scripts
package some months ago and one of its features is exactly that. It provides npm
scripts to setup and run WordPress 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/scripts
npm package by running the following command in your project folder:
npm install @wordpress/scripts --save-dev
Now add this npm script to your package.json
file:
// package.json
"scripts": {
"env": "wp-scripts env"
}
Additionally you need to configure the environment by adding the following lines to your package.json
file and adjust it to your needs (see the Block Editor Handbook for reference):
// package.json
"wp-env": {
"plugin-dir": "<Name of plugin folder inside local env>",
"plugin-name": "<Plugin name>"
}
Install WordPress
You can now run the following command to setup the local environment (You need to have Docker installed before running this command):
npm run env install
This will setup a local WordPress installation into a subdirectory of your project called wordpress/
. It also mounts the current project folder into the plugins
folder of the WordPress installation so that you can test it as you are developing it.
If you're using git in your project you probably don't want to commit the local WordPress installation. That's why you should add the wordpress/
folder to your .gitignore
file.
Start the local environment
When the setup is finished you can start the environment by running the following command:
npm run env start
Your local WordPress environment should now be running behind the port 8889
and is accessible by opening:
- Frontend: http://localhost:8889/
- Backend: http://localhost:8889/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 env stop
There are a lot of other commands which are documented here: https://developer.wordpress.org/block-editor/packages/packages-scripts/#available-sub-scripts