At Human Made my local development environment is usually a Chassis virtual machine running in Vagrant. Chassis helpfully includes WP-CLI, so whenever I find myself needing to script a change to the local WordPress environment I can quickly vagrant ssh
and start running wp
shell commands.
When I don’t need to stay logged in to the virtual machine I can provide the specific command to run as an argument to vagrant ssh
; Vagrant will run that command within the VM, show me the output, then close the connection. I find I do this a lot, whenever I want to change a setting or check the WordPress install’s state without firing up yet another browser tab:
# List active themes
vagrant ssh -c 'wp theme list'
# Install a plugin
vagrant ssh -c 'wp plugin install --activate gutenberg
# Create a user
vagrant ssh -c 'wp user create kadmin kadam@hmn.md --role=administrator --first_name="K Adam" --last_name=White --description="Local admin user"'
and so on.
In fact, I do this so often that it began to be annoying to constantly type vagrant ssh -c ''
; it’s not a lot of added keystrokes, but for a command I use more often than npm run
, they add up over time. It’d be a rejection of the developer stereotype of laziness if I didn’t try to reduce this.
So now, I’ve added this function to my .bashrc
:
# Shortcut for vagrant ssh -c 'wp ...'
vwp() {
EXTRA_ARGS=$@
vagrant ssh -c "wp $EXTRA_ARGS"
}
Now I can run any WP-CLI command I want right from my host system with this vwp
function. In most cases this saves 15 keystrokes and a lot of hassle; the only time it requires me to do anything unusual is when I want to pass multi-word arguments, in which case we do need to manually escape our quotation marks because of how Bash parses $*
.
# List active themes
vwp theme list
# Install a plugin
vwp plugin install --activate gutenberg
# Create a user
vwp user create kadmin kadam@hmn.md --role=administrator --first_name=\"K Adam\" --last_name=White --description=\"Local admin user\"
Perhaps this will be useful to you, as well; and thank you to the kind folks of the NYC JavaScript community for sharing the $@
trick a while back! ShellCheck would have you believe $*
is more correct. They’re probably right, but this works, so… ¯\_(ツ)_/¯