WP-CLI is a tool for managing your WordPress website via the command line. This may come in handy if you want to manage your WP instance without going through the web interface, or automate certain operations (change of Settings, perform backup etc.)
For example, here is a sequence of commands for installing a fresh copy of wordpress:
1 2 3 4 | $ mkdir myWordpress && cd myWordpress $ wp core download $ wp core config --dbname=mywordpress --dbuser=wordpress --dbpass=wordpress1234 --dbhost=localhost --dbcollate=utf8_general_ci $ wp core install --url=http://mywordpress.com/ --title=MyWordpress --admin_user=admin --admin_password=admin1234 --admin_email=jason@madcoda.com |
Installing WP-CLI as a command
1 2 3 4 5 | $ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar $ chmod +x wp-cli.phar $ sudo mv wp-cli.phar /usr/local/bin/wp # Done! Now test it out $ wp --info |
Using MAMP on OSX
You may find trouble connecting to the Database using wp-cli if you’re using MAMP. It is because the MySQL socket file is not located at the default location.
Method 1: symoblic link /tmp/mysql.sock to MAMP
I think this solution is quite neat, it should work most of this time, since PHP look for /tmp/mysql.sock by default
1 | $ ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock |
Method 2: Update php.ini
Find the php.ini by typing “php –ini” in the Terminal
1 2 | $ php --ini $ vi /etc/php.ini ## maybe different in your computer |
Edit the php.ini, change the default_socket
1 2 3 4 5 6 | # PDO pdo_mysql.default_socket=/Applications/MAMP/tmp/mysql/mysql.sock # MySQL mysql.default_socket = /Applications/MAMP/tmp/mysql/mysql.sock # MySQLi mysqli.default_socket = /Applications/MAMP/tmp/mysql/mysql.sock |
Dependency on the “mysql” command
Some sub-command in the wp-cli (e.g. wp core install) requires the “mysql” command line tool, you should have it installed
1 2 3 4 5 6 | # CentOS/Fedora/RHEL $ sudo yum install mysql # Debian/Ubuntu $ sudo apt-get install mysql # OSX $ brew install mysql |
Usage Example: Automate configuration of a fresh WordPress installation
There are a bunch of configs that must be changed after a fresh-install, you can save the commands as a bash file to automate your workflow
1 2 3 4 5 | wp option update time_format 'g:i A' wp option update timezone_string 'Asia/Hong_Kong' wp option update start_of_week 0 wp option update permalink_structure '/%postname%/' wp option update uploads_use_yearmonth_folders 0 |