WP-CLI aliases and shell functions for local development
WP-CLI can run commands against other installations over SSH: wp @production plugin list lists the plugins on the live server, wp @staging db export makes a dump on staging. With aliases for every environment and two or three shell functions, pulling a fresh copy of the live database to your machine becomes a single command instead of a checklist.
Problem: Refreshing the local copy from production means logging in to the server, exporting the database, copying it, importing it, replacing the URLs and deactivating the caching and mail plugins, every time by hand.
Solution: Define @local, @staging and @production aliases in wp-cli.yml, and write a shell function that streams wp @production db export - into wp @local db import -, runs search-replace and deactivates the plugins that must not run locally.
The aliases
# wp-cli.yml in the project root (or ~/.wp-cli/config.yml for all projects) @local: path: /Users/me/Sites/example url: http://example.test @staging: ssh: deploy@staging.example.com/var/www/example url: https://staging.example.com @production: ssh: deploy@example.com/var/www/example url: https://example.com
The ssh value is user@host/path; WP-CLI connects with your SSH key and runs the command on the server, where WP-CLI must be installed as well. An alias group runs a command everywhere: @all: [ '@local', '@staging', '@production' ], then wp @all core version.
wp @production core version wp @staging plugin list --status=active wp @production cron event list --fields=hook,next_run_relative
Pull production to local
# ~/.zshrc or ~/.bashrc
wp_pull() {
set -e
wp @local db export "$HOME/backups/local-$(date +%F-%H%M).sql"
wp @production db export - | wp @local db import -
wp @local search-replace 'https://example.com' 'http://example.test' --skip-columns=guid --all-tables-with-prefix --quiet
wp @local plugin deactivate wp-rocket wp-mail-smtp --quiet || true
wp @local cache flush
echo "Local database now matches production."
}
db export - writes the dump to standard output, and db import - reads it, so the dump goes through the SSH connection without a temporary file on the server. The local backup comes first, in case the import replaced something you still needed. Deactivating mail and caching plugins locally prevents real customers from getting test emails and cached production URLs.
Smaller helpers
alias wpl='wp @local'
wp_log() { ssh deploy@example.com "tail -n 50 /var/www/example/wp-content/debug.log"; }
More everyday commands: essential WP-CLI commands.
NOTE: A production database contains customer data. Keep the local copies encrypted on your disk and delete old dumps, or anonymize the users and orders after the import (for example with a wp @local eval-file anonymize.php script) when the copy goes to other developers. Never run the pull function in the other direction: production must not receive a local database.