Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:25:40 +08:00
commit 121cc922c9
7 changed files with 1995 additions and 0 deletions

338
skills/wp-env/SKILL.md Normal file
View File

@@ -0,0 +1,338 @@
---
name: wp-env
description: Local WordPress development environment management using @wordpress/env for plugin and theme development. Use this skill when setting up, configuring, starting, stopping, or managing wp-env Docker-based WordPress environments.
---
# wp-env - WordPress Local Development Environment
This skill provides assistance for working with `wp-env`, a tool that sets up local WordPress development environments using Docker with minimal configuration.
## About wp-env
`wp-env` (`@wordpress/env`) creates Docker-based WordPress environments for plugin and theme development. It provides:
- **Zero-config setup** - Works out of the box for plugins and themes
- **Dual environments** - Separate development (port 8888) and testing (port 8889) instances
- **Pre-configured tools** - Includes WP-CLI, Composer, PHPUnit, and Xdebug
- **Flexible configuration** - Customize via `.wp-env.json` for complex setups
**Default Access:**
- Development site: <http://localhost:8888>
- Testing site: <http://localhost:8889>
- Login: username `admin`, password `password`
- Database: user `root`, password `password`
## Prerequisites Check
Before working with wp-env, verify these dependencies are installed and running:
```bash
# Check Docker is installed and running
docker --version
docker ps
# Check Node.js and npm
node --version
npm --version
# Check if wp-env is installed
wp-env --version
```
**If Docker is not running:** Start Docker Desktop application first - wp-env cannot function without Docker.
**If wp-env is not installed:** Install globally with `npm -g install @wordpress/env`
## Common Workflows
### First-Time Environment Setup
When setting up wp-env for the first time in a plugin or theme directory:
```bash
# 1. Ensure Docker Desktop is running
docker ps
# 2. Install wp-env globally (if not already installed)
npm -g install @wordpress/env
# 3. Navigate to your plugin or theme directory
cd /path/to/your/plugin
# 4. Start the environment (downloads WordPress, sets up containers)
wp-env start
# 5. Access the site at http://localhost:8888
# Login with admin/password
```
wp-env will automatically detect if the current directory is a plugin or theme and mount it appropriately.
### Daily Development Operations
**Starting the environment:**
```bash
# Start with existing configuration
wp-env start
# Start and update WordPress/sources
wp-env start --update
# Start with Xdebug enabled for debugging
wp-env start --xdebug
```
**Stopping the environment:**
```bash
# Stop containers (preserves data)
wp-env stop
```
**Checking environment status:**
```bash
# View running containers
docker ps
# Should show: wordpress (8888), tests-wordpress (8889), mariadb (3306)
```
### Running WP-CLI Commands
Execute WordPress CLI commands inside the environment using `wp-env run`:
```bash
# List users on development instance
wp-env run cli wp user list
# Install a plugin
wp-env run cli wp plugin install contact-form-7 --activate
# Create a test post on the testing instance
wp-env run tests-cli wp post create --post_title="Test Post" --post_status=publish
# Update permalink structure (enables REST API access)
wp-env run cli "wp rewrite structure /%postname%/"
# Open WordPress shell for interactive PHP
wp-env run cli wp shell
```
**Environment types:**
- `cli` / `wordpress` - Development environment (shares database with port 8888)
- `tests-cli` / `tests-wordpress` - Testing environment (separate database, port 8889)
**Working directory context:**
By default, commands run from WordPress root. For plugin-specific commands, use `--env-cwd`:
```bash
# Run composer install in your plugin directory
wp-env run cli --env-cwd=wp-content/plugins/your-plugin composer install
# Run PHPUnit tests in your plugin
wp-env run tests-cli --env-cwd=wp-content/plugins/your-plugin phpunit
```
### Database Reset for Testing
Reset the database to clean state:
```bash
# Reset only the tests database (default)
wp-env clean
# Reset development database
wp-env clean development
# Reset both databases
wp-env clean all
```
⚠️ **Warning:** This permanently deletes all posts, pages, media, and custom data.
### Viewing Logs
Monitor PHP errors and Docker container logs:
```bash
# View development environment logs (follows/watches by default)
wp-env logs
# View testing environment logs
wp-env logs tests
# View both environments
wp-env logs all
# Disable following/watching
wp-env logs --watch=false
```
### Working with Ports
If the default port 8888 conflicts with another service:
```bash
# Using environment variables
WP_ENV_PORT=3333 wp-env start
# Check which ports are in use
docker ps
```
Or configure ports in `.wp-env.json`:
```json
{
"port": 3333,
"testsPort": 3334
}
```
Note: Environment variables take precedence over `.wp-env.json` values.
## Quick Reference - Essential Commands
| Command | Description |
| ---------------------------------- | --------------------------------------------- |
| `wp-env start` | Start the environment |
| `wp-env start --update` | Start and update WordPress/sources |
| `wp-env stop` | Stop the environment |
| `wp-env clean [env]` | Reset database (env: tests, development, all) |
| `wp-env destroy` | Completely remove containers and data |
| `wp-env logs [env]` | View logs (env: development, tests, all) |
| `wp-env run <container> <command>` | Execute command in container |
| `wp-env install-path` | Show where environment files are stored |
| `docker ps` | Check which containers are running |
**Common containers for `wp-env run`:**
- `cli` - WP-CLI, Composer, PHPUnit (development)
- `tests-cli` - WP-CLI, Composer, PHPUnit (testing)
- `wordpress` - WordPress PHP environment (development)
- `tests-wordpress` - WordPress PHP environment (testing)
## Configuration with .wp-env.json
Create a `.wp-env.json` file in your project root to customize the environment.
### Common Configuration Patterns
**Basic plugin development:**
```json
{
"plugins": ["."]
}
```
**Custom WordPress version:**
```json
{
"core": "WordPress/WordPress#6.4.0",
"plugins": ["."]
}
```
**Multi-plugin setup:**
```json
{
"plugins": [".", "WordPress/classic-editor", "../another-plugin"]
}
```
For complete configuration reference with 20+ examples, environment-specific overrides, custom mappings, multisite setup, and lifecycle scripts, see [references/configuration-guide.md](references/configuration-guide.md).
## When Things Go Wrong
### Common Errors
**Error: "Error while running docker-compose command"**
- Check that Docker Desktop is started and running
- Check Docker Desktop dashboard for logs, restart, or remove existing virtual machines
- Then try rerunning `wp-env start`
**Error: "Host is already in use by another container"**
- The container you are attempting to start is already running, or another container is. You can stop an existing container by running `wp-env stop` from the directory that you started it in
- If you do not remember the directory where you started `wp-env`, you can stop all containers by running `docker stop $(docker ps -q)`. This will stop all Docker containers, so use with caution
- Then try rerunning `wp-env start`
For comprehensive troubleshooting including Ubuntu Docker setup, database issues, and advanced debugging, see [references/troubleshooting.md](references/troubleshooting.md).
## Advanced Features
For detailed information on these features, see [references/command-reference.md](references/command-reference.md).
**Xdebug:** Enable step debugging with `wp-env start --xdebug`. Configure your IDE for port 9003.
**PHPUnit:** WordPress test files included. Run with `wp-env run tests-cli --env-cwd=wp-content/plugins/your-plugin phpunit`.
**Composer:** Execute commands with `wp-env run cli --env-cwd=wp-content/plugins/your-plugin composer install`.
## Best Practices
### Directory Context
- Run `wp-env start` from your plugin or theme directory for automatic mounting
- Use `--env-cwd` when running commands that need to execute in specific directories
- Use absolute paths when possible to avoid confusion
### Development Workflow
1. Start environment once per work session: `wp-env start`
2. Make code changes - they're immediately reflected (no rebuild needed)
3. Use `wp-env run cli wp` commands for WordPress operations
4. Check logs when debugging: `wp-env logs`
5. Stop when done: `wp-env stop`
### Testing Workflow
1. Use `tests-cli` and `tests-wordpress` for isolated testing
2. Reset test database frequently: `wp-env clean tests`
3. Keep test and development environments separate
4. Use `wp-env clean all` before running full integration tests
### Configuration Management
- Keep `.wp-env.json` in version control for team consistency
- Use `.wp-env.override.json` (gitignored) for local-only overrides
- Document custom configurations in project README
## Where Files Are Stored
wp-env stores files in a home directory (defaults vary by platform):
```bash
# Get the install path for current project
wp-env install-path
# Default locations:
# macOS/Windows: ~/.wp-env/$md5_of_project_path
# Linux: ~/wp-env/$md5_of_project_path
```
Override with `WP_ENV_HOME` environment variable:
```bash
WP_ENV_HOME="./local-wp-env" wp-env start
```
## Additional Resources
- **Command Reference:** [references/command-reference.md](references/command-reference.md) - Complete CLI documentation
- **Configuration Guide:** [references/configuration-guide.md](references/configuration-guide.md) - All `.wp-env.json` options
- **Troubleshooting:** [references/troubleshooting.md](references/troubleshooting.md) - Common issues and solutions
External documentation:
- [@wordpress/env npm package](https://www.npmjs.com/package/@wordpress/env)
- [WordPress Developer Handbook - wp-env](https://developer.wordpress.org/block-editor/getting-started/devenv/get-started-with-wp-env/)
- [Docker Desktop](https://docs.docker.com/desktop/)

View File

@@ -0,0 +1,665 @@
# wp-env Command Reference
Complete reference for all `wp-env` commands, options, and environment variables.
## Command Overview
| Command | Description |
|---------|-------------|
| `wp-env start` | Install and start the WordPress environment |
| `wp-env stop` | Stop the WordPress environment |
| `wp-env clean` | Clean the WordPress databases |
| `wp-env run` | Run arbitrary commands in containers |
| `wp-env destroy` | Destroy the WordPress environment completely |
| `wp-env logs` | Display PHP and Docker logs |
| `wp-env install-path` | Get the path where environment files are stored |
## wp-env start
Installs and initializes the WordPress environment, including downloading specified remote sources.
```
wp-env start [options]
```
### Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--debug` | boolean | `false` | Enable debug output |
| `--update` | boolean | `false` | Download source updates and apply WordPress configuration |
| `--xdebug` | string | - | Enable Xdebug (see Xdebug section below) |
| `--spx` | string | - | Enable SPX profiling (see SPX section below) |
| `--scripts` | boolean | `true` | Execute any configured lifecycle scripts |
### Behavior
- On first run: Downloads WordPress, creates containers, initializes environment
- Subsequent runs: Starts existing environment without changes
- With `--update`: Re-downloads sources and re-applies configuration (doesn't overwrite content)
### Environment Variables
These environment variables override `.wp-env.json` settings:
| Variable | Description | Example |
|----------|-------------|---------|
| `WP_ENV_PORT` | Development environment web server port | `WP_ENV_PORT=3333 wp-env start` |
| `WP_ENV_TESTS_PORT` | Testing environment web server port | `WP_ENV_TESTS_PORT=3334 wp-env start` |
| `WP_ENV_MYSQL_PORT` | MySQL port for development environment | `WP_ENV_MYSQL_PORT=13306 wp-env start` |
| `WP_ENV_TESTS_MYSQL_PORT` | MySQL port for testing environment | `WP_ENV_TESTS_MYSQL_PORT=13307 wp-env start` |
| `WP_ENV_PHPMYADMIN_PORT` | phpMyAdmin port for development | `WP_ENV_PHPMYADMIN_PORT=9001 wp-env start` |
| `WP_ENV_TESTS_PHPMYADMIN_PORT` | phpMyAdmin port for testing | `WP_ENV_TESTS_PHPMYADMIN_PORT=9002 wp-env start` |
| `WP_ENV_HOME` | Directory for wp-env files | `WP_ENV_HOME="./local" wp-env start` |
| `WP_ENV_CORE` | WordPress version/source | `WP_ENV_CORE="WordPress/WordPress#trunk" wp-env start` |
| `WP_ENV_PHP_VERSION` | PHP version to use | `WP_ENV_PHP_VERSION="8.0" wp-env start` |
| `WP_ENV_MULTISITE` | Enable multisite | `WP_ENV_MULTISITE=true wp-env start` |
Note: Environment variables take precedence over `.wp-env.json` values.
### Xdebug Support
Enable Xdebug for debugging PHP code:
```bash
# Enable with default "debug" mode
wp-env start --xdebug
# Enable with specific modes
wp-env start --xdebug=profile,trace,debug
# When using npm run (in local project dependencies)
npm run wp-env start -- --xdebug
```
**Xdebug Modes:**
- `debug` - Step debugging (default when --xdebug is used)
- `develop` - Development aids
- `coverage` - Code coverage analysis
- `gcstats` - Garbage collection statistics
- `profile` - Profiling
- `trace` - Function trace
See [Xdebug documentation](https://xdebug.org/docs/all_settings#mode) for mode details.
**Requirements:**
- PHP version >= 7.2 (Xdebug won't install on legacy PHP versions)
- IDE configuration for port 9003
**IDE Configuration Example (VS Code):**
```json
{
"name": "Listen for XDebug",
"type": "php",
"request": "launch",
"port": 9003,
"pathMappings": {
"/var/www/html/wp-content/plugins/your-plugin": "${workspaceFolder}/"
}
}
```
### SPX Profiling
SPX is a lightweight profiling extension with a built-in web UI:
```bash
# Enable SPX profiling
wp-env start --spx
# With specific mode
wp-env start --spx=enabled
```
**Access SPX UI:**
- Development: <http://localhost:8888/?SPX_KEY=dev&SPX_UI_URI=/>
- Testing: <http://localhost:8889/?SPX_KEY=dev&SPX_UI_URI=/>
**SPX Features:**
- Flame graphs and performance metrics
- Function call timelines
- Memory usage analysis
- Minimal performance overhead
See [SPX documentation](https://github.com/NoiseByNorthwest/php-spx) for details.
### Examples
```bash
# Basic start
wp-env start
# Start with updates
wp-env start --update
# Start with custom port
WP_ENV_PORT=4000 wp-env start
# Start with Xdebug enabled
wp-env start --xdebug
# Start with multisite and custom PHP version
WP_ENV_MULTISITE=true WP_ENV_PHP_VERSION="8.1" wp-env start
# Start with debug output
wp-env start --debug
```
## wp-env stop
Stops running WordPress containers and frees the ports.
```
wp-env stop [options]
```
### Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--debug` | boolean | `false` | Enable debug output |
### Behavior
- Stops all containers for the current project
- Preserves all data (database, uploads, configuration)
- Frees ports (8888, 8889, etc.)
- Containers can be restarted with `wp-env start`
### Example
```bash
wp-env stop
```
## wp-env clean
Cleans (resets) WordPress databases.
```
wp-env clean [environment] [options]
```
### Arguments
| Argument | Choices | Default | Description |
|----------|---------|---------|-------------|
| `environment` | `all`, `development`, `tests` | `tests` | Which environment's database to clean |
### Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--debug` | boolean | `false` | Enable debug output |
| `--scripts` | boolean | `true` | Execute any configured lifecycle scripts |
### Behavior
⚠️ **Warning:** Permanently deletes all posts, pages, media, users (except admin), and other WordPress content.
- Resets database to fresh WordPress installation
- Preserves WordPress core files and configuration
- Keeps admin user (username: `admin`, password: `password`)
### Examples
```bash
# Clean tests database only (default)
wp-env clean
wp-env clean tests
# Clean development database
wp-env clean development
# Clean both databases
wp-env clean all
```
## wp-env run
Runs arbitrary commands in Docker containers.
```
wp-env run <container> <command> [options]
```
### Arguments
| Argument | Type | Description |
|----------|------|-------------|
| `container` | string (required) | The Docker service to run the command on |
| `command` | string (required) | The command to run |
### Available Containers
| Container | Description | Available Tools |
|-----------|-------------|-----------------|
| `cli` | WP-CLI environment (development) | wp-cli, composer, phpunit, bash |
| `tests-cli` | WP-CLI environment (testing) | wp-cli, composer, phpunit, bash |
| `wordpress` | WordPress PHP environment (development) | php |
| `tests-wordpress` | WordPress PHP environment (testing) | php |
| `mysql` | MySQL database (development) | mysql |
| `tests-mysql` | MySQL database (testing) | mysql |
| `composer` | Composer environment | composer |
| `phpmyadmin` | phpMyAdmin (if enabled) | - |
### Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--debug` | boolean | `false` | Enable debug output |
| `--env-cwd` | string | `"."` | Working directory inside container (relative to WordPress root) |
### Working Directory
- Default: WordPress root (`/var/www/html`)
- Paths without leading slash are relative to WordPress root
- Use `--env-cwd` for commands that need specific directory context
### Argument Parsing
Commands with options that conflict with wp-env options require `--` separator:
```bash
# This shows wp-env help (--help interpreted by wp-env)
wp-env run cli php --help
# This shows PHP help (--help passed to php)
wp-env run cli php -- --help
```
### Examples
#### WP-CLI Commands
```bash
# List users
wp-env run cli wp user list
# Install and activate a plugin
wp-env run cli wp plugin install contact-form-7 --activate
# Create a post on tests instance
wp-env run tests-cli wp post create --post_title="Test" --post_status=publish
# Update permalink structure
wp-env run cli "wp rewrite structure /%postname%/"
# Open WordPress shell (interactive PHP)
wp-env run cli wp shell
```
#### Composer Commands
```bash
# Run composer install in a plugin directory
wp-env run cli --env-cwd=wp-content/plugins/your-plugin composer install
# Update dependencies
wp-env run cli --env-cwd=wp-content/plugins/your-plugin composer update
# Show installed packages
wp-env run cli --env-cwd=wp-content/plugins/your-plugin composer show
```
#### PHPUnit Commands
```bash
# Run tests in a plugin
wp-env run tests-cli --env-cwd=wp-content/plugins/your-plugin phpunit
# Run specific test file
wp-env run tests-cli --env-cwd=wp-content/plugins/your-plugin phpunit tests/test-sample.php
# Run with coverage
wp-env run tests-cli --env-cwd=wp-content/plugins/your-plugin phpunit --coverage-html coverage
```
#### Shell Access
```bash
# Open bash shell in CLI container
wp-env run cli bash
# Open bash in tests container
wp-env run tests-cli bash
# Run a bash script
wp-env run cli bash /var/www/html/wp-content/plugins/your-plugin/scripts/setup.sh
```
#### Direct PHP Execution
```bash
# Run PHP script
wp-env run cli php /var/www/html/wp-content/plugins/your-plugin/scripts/migrate.php
# Execute PHP code directly
wp-env run cli php -r "echo phpversion();"
```
## wp-env destroy
Destroys the WordPress environment completely.
```
wp-env destroy [options]
```
### Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--debug` | boolean | `false` | Enable debug output |
| `--scripts` | boolean | `true` | Execute any configured lifecycle scripts |
### Behavior
⚠️ **Warning:** Permanently deletes:
- All Docker containers
- All Docker volumes (databases, uploads, etc.)
- All Docker networks
- All local files in the wp-env home directory
Use this when:
- Environment is corrupted beyond repair
- Need to start completely fresh
- Freeing up disk space
- Removing wp-env from a project
### Example
```bash
# Destroy everything
wp-env destroy
# Create fresh environment
wp-env start
```
## wp-env logs
Displays PHP and Docker logs for the WordPress environment.
```
wp-env logs [environment] [options]
```
### Arguments
| Argument | Choices | Default | Description |
|----------|---------|---------|-------------|
| `environment` | `development`, `tests`, `all` | `development` | Which environment to display logs from |
### Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--debug` | boolean | `false` | Enable debug output |
| `--watch` | boolean | `true` | Watch for logs as they happen (follow mode) |
### Behavior
- Shows PHP error logs and Docker container logs
- By default, follows/tails logs in real-time (press Ctrl+C to stop)
- Use `--watch=false` to show current logs and exit
### Examples
```bash
# View development logs (follows by default)
wp-env logs
# View testing environment logs
wp-env logs tests
# View both environments
wp-env logs all
# Show logs without following
wp-env logs --watch=false
# View with debug output
wp-env logs --debug
```
## wp-env install-path
Gets the path where all environment files are stored.
```
wp-env install-path
```
### Behavior
Returns the absolute path to the directory containing:
- Docker files and configurations
- Downloaded WordPress core
- PHPUnit files
- Downloaded plugins, themes, and other sources
### Path Format
- Default location: `$WP_ENV_HOME/$md5_of_project_path`
- macOS/Windows default: `~/.wp-env/$md5_of_project_path`
- Linux default: `~/wp-env/$md5_of_project_path` (for Snap compatibility)
### Example
```bash
$ wp-env install-path
/home/user/.wp-env/63263e6506becb7b8613b02d42280a49
```
## Global Options
Options available for all commands:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--debug` | boolean | `false` | Enable debug output for troubleshooting |
| `--help` | boolean | `false` | Show help for the command |
| `--version` | boolean | `false` | Show wp-env version number |
## Lifecycle Scripts
Lifecycle scripts run automatically at certain points. Configure in `.wp-env.json`:
```json
{
"lifecycleScripts": {
"afterStart": "node scripts/setup-e2e.js",
"afterClean": "echo 'Database cleaned'",
"afterDestroy": "rm -rf custom-cache"
}
}
```
### Available Lifecycle Events
| Event | When It Runs | Use Cases |
|-------|--------------|-----------|
| `afterStart` | After `wp-env start` completes | Bootstrap data, run migrations, configure environment |
| `afterClean` | After `wp-env clean` completes | Log cleanup, reset custom data |
| `afterDestroy` | After `wp-env destroy` completes | Clean up external resources |
### Environment Variable Override
Override lifecycle scripts via environment variables:
```bash
WP_ENV_LIFECYCLE_SCRIPT_AFTER_START="npm run bootstrap" wp-env start
```
Format: `WP_ENV_LIFECYCLE_SCRIPT_{EVENT_NAME}` (uppercase, snake_case)
## Exit Codes
All wp-env commands use standard exit codes:
| Code | Meaning |
|------|---------|
| `0` | Success |
| `1` | Error (see error message for details) |
## Tips and Best Practices
### Using with npm Scripts
Add wp-env commands to `package.json` for convenience:
```json
{
"scripts": {
"wp-env": "wp-env",
"env:start": "wp-env start",
"env:stop": "wp-env stop",
"env:clean": "wp-env clean all && wp-env start",
"env:reset": "wp-env destroy && wp-env start",
"wp": "wp-env run cli wp",
"composer": "wp-env run cli --env-cwd=wp-content/plugins/your-plugin composer",
"test": "wp-env run tests-cli --env-cwd=wp-content/plugins/your-plugin phpunit"
}
}
```
Then use: `npm run env:start`, `npm run test`, etc.
### Passing Flags to npm Scripts
When using `npm run wp-env`, use `--` to pass flags:
```bash
# Wrong: --update goes to npm, not wp-env
npm run env:start --update
# Right: --update passed to wp-env
npm run env:start -- --update
```
### Command Chaining
Chain commands for complex workflows:
```bash
# Reset and start fresh
wp-env clean all && wp-env start
# Destroy, recreate, and install a plugin
wp-env destroy && wp-env start && wp-env run cli wp plugin install woocommerce --activate
```
### Checking Environment Status
Verify wp-env is running properly:
```bash
# Check running containers
docker ps
# Should show three containers by default:
# - wordpress (port 8888)
# - tests-wordpress (port 8889)
# - mariadb (port 3306)
# Check wp-env version
wp-env --version
# View install path
wp-env install-path
```
### Working with Multiple Projects
Each project has its own isolated environment:
```bash
# Project 1
cd ~/projects/plugin-a
wp-env start # Uses port 8888
# Project 2 (different port)
cd ~/projects/plugin-b
WP_ENV_PORT=4000 wp-env start # Uses port 4000
```
## WordPress PHPUnit Tests
wp-env includes WordPress' PHPUnit test files automatically.
### Environment Variable
- `WP_TESTS_DIR` - Points to PHPUnit test files location within containers
- Files correspond to the installed WordPress version
### Custom wp-tests-config.php
Override the default test configuration:
```php
// In your bootstrap.php file
define('WP_TESTS_CONFIG_FILE_PATH', '/path/to/custom/wp-tests-config.php');
```
WordPress will use your custom file instead of the default.
### Running Tests
```bash
# Run all tests
wp-env run tests-cli --env-cwd=wp-content/plugins/your-plugin phpunit
# Run specific test file
wp-env run tests-cli --env-cwd=wp-content/plugins/your-plugin phpunit tests/test-sample.php
# Run with bootstrap file
wp-env run tests-cli --env-cwd=wp-content/plugins/your-plugin phpunit --bootstrap=tests/bootstrap.php
```
## Database Access
Direct database access credentials:
| Environment | Host | Port | User | Password | Database |
|-------------|------|------|------|----------|----------|
| Development | `localhost` | `WP_ENV_MYSQL_PORT` (random if not set) | `root` | `password` | `wordpress` |
| Testing | `localhost` | `WP_ENV_TESTS_MYSQL_PORT` (random if not set) | `root` | `password` | `wordpress-tests` |
**Note:** MySQL ports are not exposed by default. Set `WP_ENV_MYSQL_PORT` or `WP_ENV_TESTS_MYSQL_PORT` to expose them.
### Connecting with MySQL Client
```bash
# Expose MySQL port first
WP_ENV_MYSQL_PORT=13306 wp-env start
# Connect from host
mysql -h 127.0.0.1 -P 13306 -u root -ppassword wordpress
```
### Using phpMyAdmin
```bash
# Enable phpMyAdmin on port 9001
WP_ENV_PHPMYADMIN_PORT=9001 wp-env start
# Access at http://localhost:9001
# Login: root / password
```
Or configure in `.wp-env.json`:
```json
{
"phpmyadminPort": 9001
}
```

View File

@@ -0,0 +1,838 @@
# wp-env Configuration Guide
Complete guide to configuring wp-env using `.wp-env.json` and `.wp-env.override.json` files.
## Configuration File Overview
wp-env supports two configuration files:
1. **`.wp-env.json`** - Primary configuration, typically version controlled
2. **`.wp-env.override.json`** - Local overrides, typically gitignored
Place these files in your project root (where you run `wp-env start`).
## Basic Configuration Structure
```json
{
"core": null,
"phpVersion": null,
"plugins": [],
"themes": [],
"port": 8888,
"testsPort": 8889,
"config": {},
"mappings": {},
"mysqlPort": null,
"phpmyadminPort": null,
"multisite": false,
"lifecycleScripts": {},
"env": {
"development": {},
"tests": {}
}
}
```
## Configuration Fields
### Core WordPress Installation
**Field:** `core`
**Type:** `string | null`
**Default:** `null` (latest production WordPress)
Specifies which WordPress installation to use.
```json
{
"core": null
}
```
**Options:**
| Value Type | Format | Example |
|------------|--------|---------|
| Latest WordPress | `null` | `"core": null` |
| Specific version | `"WordPress/WordPress#<version>"` | `"core": "WordPress/WordPress#6.4.0"` |
| Development trunk | `"WordPress/WordPress#master"` | `"core": "WordPress/WordPress#master"` |
| Local path (relative) | `".<path>"` or `"~<path>"` | `"core": "../wordpress-develop/build"` |
| Local path (absolute) | `"/<path>"` or `"<letter>:\<path>"` | `"core": "/Users/you/wordpress"` |
| Git repository | `"<owner>/<repo>#<ref>"` | `"core": "WordPress/WordPress#trunk"` |
| SSH repository | `"ssh://user@host/<path>.git#<ref>"` | `"core": "ssh://git@github.com/WordPress/WordPress.git"` |
| ZIP file | `"http[s]://<url>.zip"` | `"core": "https://wordpress.org/wordpress-6.4.zip"` |
**Environment Variable Override:** `WP_ENV_CORE`
```bash
WP_ENV_CORE="WordPress/WordPress#trunk" wp-env start
```
### PHP Version
**Field:** `phpVersion`
**Type:** `string | null`
**Default:** `null` (default WordPress production PHP version)
Specifies the PHP version to use.
```json
{
"phpVersion": "8.1"
}
```
**Supported versions:** Any version supported by WordPress (e.g., "7.4", "8.0", "8.1", "8.2")
**Environment Variable Override:** `WP_ENV_PHP_VERSION`
```bash
WP_ENV_PHP_VERSION="8.1" wp-env start
```
### Plugins
**Field:** `plugins`
**Type:** `string[]`
**Default:** `[]`
List of plugins to install and activate.
```json
{
"plugins": [
".",
"WordPress/classic-editor",
"../my-local-plugin",
"https://downloads.wordpress.org/plugin/akismet.zip"
]
}
```
**Source Types:** Same as `core` field (paths, GitHub repos, ZIP files, etc.)
**Behavior:**
- All plugins are automatically activated
- Current directory (`.`) is auto-detected as a plugin if it contains a plugin header
- Use `mappings` instead if you don't want auto-activation
### Themes
**Field:** `themes`
**Type:** `string[]`
**Default:** `[]`
List of themes to install.
```json
{
"themes": [
".",
"WordPress/theme-experiments"
]
}
```
**Source Types:** Same as `core` field
**Behavior:**
- Themes are installed but not activated
- Activate via WP-CLI: `wp-env run cli wp theme activate your-theme`
### Ports
**Field:** `port`
**Type:** `integer`
**Default:** `8888`
Primary port for the development environment.
```json
{
"port": 4000
}
```
**Access:** <http://localhost:4000>
**Environment Variable Override:** `WP_ENV_PORT` (takes precedence)
```bash
WP_ENV_PORT=4000 wp-env start
```
---
**Field:** `testsPort`
**Type:** `integer`
**Default:** `8889`
Port for the testing environment.
```json
{
"testsPort": 4001
}
```
**Environment Variable Override:** `WP_ENV_TESTS_PORT`
### MySQL Port
**Field:** `mysqlPort`
**Type:** `integer | null`
**Default:** `null` (not exposed to host)
Expose MySQL port to the host machine.
```json
{
"env": {
"development": {
"mysqlPort": 13306
},
"tests": {
"mysqlPort": 13307
}
}
}
```
**Note:** Only available in `env.development` and `env.tests` objects, not at root level.
**Environment Variable Override:**
- `WP_ENV_MYSQL_PORT` (development)
- `WP_ENV_TESTS_MYSQL_PORT` (tests)
**Connection:**
```bash
mysql -h 127.0.0.1 -P 13306 -u root -ppassword wordpress
```
### phpMyAdmin Port
**Field:** `phpmyadminPort`
**Type:** `integer | null`
**Default:** `null` (disabled)
Enable phpMyAdmin web interface.
```json
{
"phpmyadminPort": 9001
}
```
**Access:** <http://localhost:9001>
**Login:** username: `root`, password: `password`
**Environment Variable Override:**
- `WP_ENV_PHPMYADMIN_PORT` (development)
- `WP_ENV_TESTS_PHPMYADMIN_PORT` (tests)
### WP-Config Constants
**Field:** `config`
**Type:** `Object`
**Default:** See Default Constants section
Define wp-config.php constants.
```json
{
"config": {
"WP_DEBUG_LOG": true,
"WP_DEBUG_DISPLAY": false,
"CUSTOM_CONSTANT": "custom-value"
}
}
```
**Special Values:**
- Set to `null` to prevent a constant from being defined
- Boolean, string, and numeric values supported
**Merging Behavior:**
- `config` values are merged between root and `env.*` objects
- Environment-specific values override root values
### Default Constants
**Development Environment:**
```json
{
"WP_DEBUG": true,
"SCRIPT_DEBUG": true,
"WP_PHP_BINARY": "php",
"WP_TESTS_EMAIL": "admin@example.org",
"WP_TESTS_TITLE": "Test Blog",
"WP_TESTS_DOMAIN": "localhost",
"WP_SITEURL": "http://localhost:8888",
"WP_HOME": "http://localhost:8888"
}
```
**Test Environment:**
Same as development, but `WP_DEBUG` and `SCRIPT_DEBUG` are `false`.
**URLs include configured ports:**
If `port: 4000`, then `WP_HOME` becomes `http://localhost:4000`.
### Directory Mappings
**Field:** `mappings`
**Type:** `Object`
**Default:** `{}`
Map local directories to WordPress directories.
```json
{
"mappings": {
"wp-content/mu-plugins": "./mu-plugins",
"wp-content/themes/my-theme": "./themes/my-theme",
"wp-content/plugins/test-plugin": "../test-plugin",
".htaccess": "./.htaccess"
}
}
```
**Use Cases:**
- Add mu-plugins (must-use plugins)
- Mount multiple themes without activating them
- Add plugins without auto-activation
- Map custom directories
- Configure PHP settings via .htaccess
**Merging Behavior:**
- `mappings` values are merged between root and `env.*` objects
- Use for environment-specific mounts
### Multisite
**Field:** `multisite`
**Type:** `boolean`
**Default:** `false`
Enable WordPress multisite installation.
```json
{
"multisite": true
}
```
**Environment Variable Override:** `WP_ENV_MULTISITE`
```bash
WP_ENV_MULTISITE=true wp-env start
```
### Lifecycle Scripts
**Field:** `lifecycleScripts`
**Type:** `Object`
**Default:** `{}`
Execute commands at specific lifecycle events.
```json
{
"lifecycleScripts": {
"afterStart": "node scripts/bootstrap-data.js",
"afterClean": "echo 'Database cleaned'",
"afterDestroy": "rm -rf .cache"
}
}
```
**Available Events:**
- `afterStart` - After `wp-env start` completes
- `afterClean` - After `wp-env clean` completes
- `afterDestroy` - After `wp-env destroy` completes
**Environment Variable Override:**
```bash
WP_ENV_LIFECYCLE_SCRIPT_AFTER_START="npm run setup" wp-env start
```
Format: `WP_ENV_LIFECYCLE_SCRIPT_{EVENT}` (uppercase, snake_case)
**Disable Scripts:**
```bash
wp-env start --scripts=false
```
### Environment-Specific Configuration
**Field:** `env`
**Type:** `Object`
**Default:** `{}`
Override configuration for specific environments.
```json
{
"plugins": ["."],
"config": {
"WP_DEBUG": true
},
"env": {
"development": {
"themes": ["./my-theme"],
"port": 4000
},
"tests": {
"plugins": [".", "woocommerce"],
"config": {
"WP_DEBUG": false
},
"port": 4001,
"mysqlPort": 13306
}
}
}
```
**Merging Rules:**
- **Merged:** `config`, `mappings`
- **Replaced:** `plugins`, `themes`, `port`, `testsPort`, `core`, `phpVersion`, `multisite`
**Available Environments:**
- `development` - Main development environment (port 8888 by default)
- `tests` - Testing environment (port 8889 by default)
## Examples
### Latest stable WordPress + current directory as a plugin
This is useful for plugin development.
```json
{
"core": null,
"plugins": [ "." ]
}
```
### Latest development WordPress + current directory as a plugin
This is useful for plugin development when upstream Core changes need to be tested. This can also be set via the environment variable `WP_ENV_CORE`.
```json
{
"core": "WordPress/WordPress#master",
"plugins": [ "." ]
}
```
### Local wordpress-develop + current directory as a plugin
This is useful for working on plugins and WordPress Core at the same time.
If you are running a `build` of `wordpress-develop`, point `core` to the `build` directory.
```json
{
"core": "../wordpress-develop/build",
"plugins": [ "." ]
}
```
If you are running `wordpress-develop` in a dev mode (e.g. the `dev` watch command or the `build:dev` dev build), then point `core` to the `src` directory.
```json
{
"core": "../wordpress-develop/src",
"plugins": [ "." ]
}
```
### A complete testing environment
This is useful for integration testing: that is, testing how old versions of WordPress and different combinations of plugins and themes impact each other.
```json
{
"core": "WordPress/WordPress#5.2.0",
"plugins": [ "WordPress/wp-lazy-loading", "WordPress/classic-editor" ],
"themes": [ "WordPress/theme-experiments" ]
}
```
### Add mu-plugins and other mapped directories
You can add mu-plugins via the mapping config. The mapping config also allows you to mount a directory to any location in the wordpress install, so you could even mount a subdirectory. Note here that theme-1, will not be activated.
```json
{
"plugins": [ "." ],
"mappings": {
"wp-content/mu-plugins": "./path/to/local/mu-plugins",
"wp-content/themes": "./path/to/local/themes",
"wp-content/themes/specific-theme": "./path/to/local/theme-1"
}
}
```
### Avoid activating plugins or themes on the instance
Since all plugins in the `plugins` key are activated by default, you should use the `mappings` key to avoid this behavior. This might be helpful if you have a test plugin that should not be activated all the time.
```json
{
"plugins": [ "." ],
"mappings": {
"wp-content/plugins/my-test-plugin": "./path/to/test/plugin"
}
}
```
### Map a plugin only in the tests environment
If you need a plugin active in one environment but not the other, you can use `env.<envName>` to set options specific to one environment. Here, we activate cwd and a test plugin on the tests instance. This plugin is not activated on any other instances.
```json
{
"plugins": [ "." ],
"env": {
"tests": {
"plugins": [ ".", "path/to/test/plugin" ]
}
}
}
```
### Custom Port Numbers
You can tell `wp-env` to use a custom port number so that your instance does not conflict with other `wp-env` instances.
```json
{
"plugins": [ "." ],
"port": 4013,
"env": {
"tests": {
"port": 4012
}
}
}
```
These can also be set via environment variables:
- `WP_ENV_PORT` to override the development environment's web server's port.
- `WP_ENV_TESTS_PORT` to override the testing environment's web server's port.
- phpMyAdmin is not enabled by default, but its port can also be overridden for the development and testing environments via `WP_ENV_PHPMYADMIN_PORT` and `WP_ENV_TESTS_PHPMYADMIN_PORT`, respectively.
- By default, MySQL aren't exposed to the host, which means no chance of port conflicts. But these can also be overridden for the development and testing environments via `WP_ENV_MYSQL_PORT` and `WP_ENV_TESTS_MYSQL_PORT`, respectively.
### Specific PHP Version
You can tell `wp-env` to use a specific PHP version for compatibility and testing. This can also be set via the environment variable `WP_ENV_PHP_VERSION`.
```json
{
"phpVersion": "7.2",
"plugins": [ "." ]
}
```
### Multisite support
You can tell `wp-env` if the site should be multisite enabled. This can also be set via the environment variable `WP_ENV_MULTISITE`.
```json
{
"multisite": true,
"plugins": [ "." ]
}
```
### Node Lifecycle Script
This is useful for performing some actions after setting up the environment, such as bootstrapping an E2E test environment.
```json
{
"lifecycleScripts": {
"afterStart": "node tests/e2e/bin/setup-env.js"
}
}
```
### Advanced PHP settings
You can set PHP settings by mapping an `.htaccess` file. This maps an `.htaccess` file to the WordPress root (`/var/www/html`) from the directory in which you run `wp-env`.
```json
{
"mappings": {
".htaccess": ".htaccess"
}
}
```
Then, your .htaccess file can contain various settings like this:
```
# Note: the default upload value is 1G.
php_value post_max_size 2G
php_value upload_max_filesize 2G
php_value memory_limit 2G
```
This is useful if there are options you'd like to add to `php.ini`, which is difficult to access in this environment.
### Using SPX Profiling
SPX is a simple profiling extension for PHP that provides low-overhead profiling with a built-in web UI. When enabled with `--spx`, you can access the SPX profiling interface to analyze your application's performance.
To enable SPX profiling:
```
wp-env start --spx
```
Once enabled, you can access the SPX web UI by visiting any page in your WordPress environment with the query parameters `?SPX_KEY=dev&SPX_UI_URI=/`. For example:
- Development site: `http://localhost:8888/?SPX_KEY=dev&SPX_UI_URI=/`
- Test site: `http://localhost:8889/?SPX_KEY=dev&SPX_UI_URI=/`
From the SPX interface, you can: Enable profiling for subsequent requests View flame graphs and performance metrics Analyze function call timelines Examine memory usage and other performance data
SPX provides a more lightweight alternative to Xdebug for profiling, with minimal performance overhead and an intuitive web-based interface.
## Configuration Override System
### .wp-env.override.json
Create `.wp-env.override.json` for local-only configuration:
```json
{
"port": 3000,
"config": {
"LOCAL_SETTING": "local-value"
}
}
```
**Merging Behavior:**
- Override file values take precedence over `.wp-env.json`
- `config` and `mappings` are merged
- Other fields are replaced
**Example:**
`.wp-env.json`:
```json
{
"plugins": [".", "woocommerce"],
"config": {
"WP_DEBUG": true,
"KEY_1": "value-1"
}
}
```
`.wp-env.override.json`:
```json
{
"plugins": ["."],
"config": {
"KEY_1": "override-1",
"KEY_2": "value-2"
}
}
```
**Result:**
```json
{
"plugins": ["."],
"config": {
"WP_DEBUG": true,
"KEY_1": "override-1",
"KEY_2": "value-2"
}
}
```
**Best Practice:** Add to `.gitignore`:
```gitignore
.wp-env.override.json
```
## Environment Variables
Configuration fields can be overridden via environment variables. See [command-reference.md](command-reference.md) for the complete list of environment variables and their usage.
**Precedence:** Environment variables > `.wp-env.override.json` > `.wp-env.json`
## Source Type Reference
All configuration fields that accept sources (`core`, `plugins`, `themes`) support these formats:
| Type | Format | Example |
|------|--------|---------|
| Relative path | `.<path>` or `~<path>` | `"."`, `"../plugin"`, `"~/projects/theme"` |
| Absolute path | `/<path>` or `<letter>:\<path>` | `"/var/www/plugin"`, `"C:\\projects\\theme"` |
| GitHub repo | `<owner>/<repo>[/<path>][#<ref>]` | `"WordPress/gutenberg"`, `"WordPress/gutenberg#trunk"` |
| SSH repo | `ssh://user@host/<path>.git[#<ref>]` | `"ssh://git@github.com/WordPress/WordPress.git"` |
| ZIP file | `http[s]://<url>.zip` | `"https://downloads.wordpress.org/plugin/akismet.zip"` |
**Notes:**
- GitHub repos without `#<ref>` use the default branch
- Remote sources are downloaded to `~/.wp-env/`
- Relative paths are relative to the directory containing `.wp-env.json`
## Configuration Validation
wp-env validates configuration on startup. Common errors:
### Invalid JSON
```
Error: Failed to parse .wp-env.json
```
Fix: Validate JSON syntax (use a JSON validator or linter).
### Invalid Port Number
```
Error: Port must be a number between 0 and 65535
```
Fix: Use valid port numbers (typically 1024-65535 for user applications).
### Invalid Source Path
```
Error: Could not find source at path: /invalid/path
```
Fix: Verify local paths exist and are accessible.
### Conflicting Ports
```
Error: Port 8888 is already in use
```
Fix: Change port in configuration or stop the conflicting service.
## Best Practices
### Version Control
**Do commit:**
- `.wp-env.json` - Share configuration with team
**Don't commit:**
- `.wp-env.override.json` - Local-only settings
- `~/.wp-env/` - Downloaded sources and environment files
### Team Consistency
Use `.wp-env.json` for shared configuration:
```json
{
"core": "WordPress/WordPress#6.4.0",
"phpVersion": "8.1",
"plugins": ["."],
"config": {
"WP_DEBUG_LOG": true
}
}
```
Use `.wp-env.override.json` for personal preferences:
```json
{
"port": 4000,
"phpmyadminPort": 9001
}
```
### Documentation
Document custom configuration in your project README:
```markdown
## Local Development
This project uses wp-env for local development.
### Setup
1. Install wp-env: `npm -g install @wordpress/env`
2. Start environment: `wp-env start`
3. Access site: http://localhost:8888
### Custom Configuration
- Uses WordPress 6.4.0
- PHP 8.1
- Includes WooCommerce for testing
```
### Environment-Specific Settings
Use `env` for different needs in development vs testing:
```json
{
"plugins": ["."],
"env": {
"development": {
"plugins": [".", "query-monitor"],
"config": {
"WP_DEBUG_DISPLAY": true
}
},
"tests": {
"plugins": ["."],
"config": {
"WP_DEBUG_DISPLAY": false
}
}
}
}
```
### Minimal Configuration
Start minimal, add configuration as needed:
```json
{
"plugins": ["."]
}
```
Then add features incrementally based on requirements.

View File

@@ -0,0 +1,83 @@
# wp-env Troubleshooting Guide
Comprehensive troubleshooting for wp-env issues beyond the common errors covered in SKILL.md.
## Troubleshooting Common Problems
Many common problems can be fixed by running through the following troubleshooting steps in order:
### 1. Check that wp-env is running
First, check that `wp-env` is running. One way to do this is to have Docker print a table with the currently running containers:
```
docker ps
```
In this table, by default, you should see three entries: `wordpress` with port 8888, `tests-wordpress` with port 8889 and `mariadb` with port 3306.
### 2. Check the port number
By default `wp-env` uses port 8888, meaning that the local environment will be available at <http://localhost:8888>.
You can configure the port that `wp-env` uses so that it doesn't clash with another server by specifying the `WP_ENV_PORT` environment variable when starting `wp-env`:
```
WP_ENV_PORT=3333 wp-env start
```
Running `docker ps` and inspecting the `PORTS` column allows you to determine which port `wp-env` is currently using.
You may also specify the port numbers in your `.wp-env.json` file, but the environment variables will take precedence.
### 3. Restart wp-env with updates
Restarting `wp-env` will restart the underlying Docker containers which can fix many issues.
To restart `wp-env`, just run `wp-env start` again. It will automatically stop and start the container. If you also pass the `--update` argument, it will download updates and configure WordPress again.
```
wp-env start --update
```
### 4. Restart Docker
Restarting Docker will restart the underlying Docker containers and volumes which can fix many issues.
To restart Docker:
1. Click on the Docker icon in the system tray or menu bar.
2. Select `Restart`.
Once restarted, start `wp-env` again:
```
wp-env start
```
### 5. Reset the database
Resetting the database which the local environment uses can fix many issues, especially when they are related to the WordPress installation.
To reset the database:
⚠️ WARNING: This will permanently delete any posts, pages, media, etc. in the local WordPress installation.
```
wp-env clean all
wp-env start
```
### 6. Destroy everything and start again 🔥
When all else fails, you can use `wp-env destroy` to forcibly remove all of the underlying Docker containers, volumes, and files. This will allow you to start from scratch.
To do so:
⚠️ WARNING: This will permanently delete any posts, pages, media, etc. in the local WordPress installation.
```
$ wp-env destroy
# This new instance is a fresh start with no existing data:
$ wp-env start
```