search ]

Advanced WordPress management with WP-CLI

The command-line has always been popular among developers because it provides tools that speed up work and streamline the development process. At first glance, it’s hard to believe how using the command line to perform certain actions is faster than performing these actions through a graphical interface. The purpose of this guide is to dispel these doubts, at least in everything related to performing tasks in WordPress.

WordPress provides a graphical interface for every administrative task, which is actually why it is the most popular content management system on the web. But in terms of efficiency, working with the command line allows you to perform many actions more quickly and conveniently than from the WordPress management system.

WP-CLI is a set of tools that provide functionality for managing WordPress sites. In this guide, we will describe the advantages of using WP-CLI and demonstrate several advanced commands that will make your life easier in the WordPress development environment.


Installing WP-CLI

Note: The following steps require working in a (UNIX (OSx, Linux or FreeBSD environment, if you are using Windows you will need a tool such as Cygwin or a virtual machine.

Installing WP-CLI is simple. The basic idea is to download a PHP file and place it in a directory where it is accessible from anywhere. You can download the WP-CLI script from GitHub.

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

Then you need to allow this file to be executable:

chmod +x wp-cli.phar

The last step is to move this file to a directory so you can run it from anywhere. Changing the file name to a shorter name is also a good idea, which is why WP is the name usually used:

sudo mv wp-cli.phar /usr/local/bin/wp

With this, the installation is complete and at this point you should be able to run WP-CLI commands. You can check if the process was completed successfully by running this command:

wp --info

If your installation was successful you should see something like this:

PHP binary: /usr/bin/php
PHP version: 5.5.24
php.ini used: /etc/php.ini
WP-CLI root dir:  phar://wp-cli.phar
WP-CLI global config: /Users/kouratoras/.wp-cli/config.yml
WP-CLI project config:  
WP-CLI version: 0.19.2

Common Operations with WP-CLI

This guide focuses on more advanced operations of WP-CLI, but let’s start with a number of basic operations that can be performed with it.

Installing a WordPress Site

A basic WP-CLI command is core, which provides a set of tools for managing WordPress installations. The first step in creating a new WordPress site is to download the WordPress files. Go to the directory where you want to install WordPress and run the command:

wp core download

This command will download the latest version of WordPress in English (en_US), if you want to download a different version or language, use the –version or –locale parameters. For example, to download version 4.2.2 in Hebrew, run:

wp core download --version=4.2.2 --locale=he_IL

Once the download is complete, you can create the wp-config.php file using the core config command:

wp core config --dbname=databasename --dbuser=databaseuser --dbpass=databasepassword --dbhost=localhost --dbprefix=prfx_

The command will use these arguments to create a wp-config.php file. The final step is to install WordPress using the core install command:

wp core install --url=example.com --title="WordPress Website Title" --admin_user=admin_user --admin_password=admin_password --admin_email="admin@example.com"

Updating WordPress Version

If your version of WordPress needs updating, use the wp core update and wp core update-db commands to update WordPress source files and the database (if the database needs updating).

Updating your version of WordPress, especially with an emphasis on WordPress security updates, is particularly important. To perform these updates quickly, use the core update and core update-db commands:

wp core update 
wp core update-db

You can always check your current WordPress version with wp core version:

wp core version

Performing these actions from the command line may not seem more efficient than doing them from the management interface at first glance, but if you manage multiple WordPress sites, it can save you a lot of time. You can create a script that updates all of them in one action:

#!/bin/bash
declare -a sites=('/var/www/wp1' '/var/www/wp2' '/var/www/wp3')
for site in "${sites[@]}";
do
    wp --path=$site core update
done

In any case, it is highly recommended to backup the database before any update:

wp db export backup.sql

Managing Plugins

Similarly, managing plugins is a one-command operation. For example, wp plugin status will return information about installed plugins and their status – A = Active, I = Inactive, and UA = An update is available for this plugin.

5 installed plugins:
 UA smooth-scroll-up        0.8.9
  I wordpress-beta-tester   1.0
  A wordpress-importer      0.6.1
  A wpcli-commands          1.0

Additional commands that can be performed on plugins are install, activate, deactivate, update, delete, search, and can be used in this way:

wp plugin install wordpress-importer --activate
wp plugin deactivate wordpress-importer
wp plugin delete wordpress-importer
wp plugin update --all
wp plugin search import

Managing Themes with WP-CLI

Generally, the same commands used for managing plugins can be applied to themes by replacing the word ‘plugin’ with ‘theme’, so there’s no need to elaborate further. However, one command worth mentioning is scaffold, which creates an empty child theme and shortens the process:

wp scaffold child-theme my-child-theme --parent_theme=twentyfifteen --theme_name='My Child Theme' --author='Konstantinos Kouratoras' --author_uri=http://www.kouratoras.gr --theme_uri=http://wp.kouratoras.gr --activate

Manipulating Information with WP-CLI

Apart from simple commands like post create, post edit, and post delete, WP-CLI’s toolset provides tools for managing posts. If you need 400 posts to test your plugin’s code or the theme you created, you can use the command:

wp post generate --count=400

It’s also possible to export information and import it from another WordPress site. To do this, you need to install the wordpress-importer plugin:

wp plugin install wordpress-importer --activate

Now you can use the export and import commands to complete the task:

wp export
wp import test.xml --authors=create

Managing Post Revisions

By default, WordPress stores all post revisions in the database, which inevitably leads to a lot of data in the posts table of the database.

To address this issue, you can use a WP-CLI extension called wp-revisions-cli which enables functionality to manage post revisions. You can install this extension like any WordPress plugin, and then you’ll have the option to use commands such as clean, list, and status.


Managing Media with WP-CLI

The WordPress management interface does not allow for convenient and efficient management of images. WP-CLI provides tools that will save you a lot of time in managing the media of your WordPress site.

Importing Images

I once encountered a situation where a client provided me with a large number of images and asked me to import them into his WordPress site. Performing this through the management interface is a tedious task, but you can use the media tool of WP-CLI to perform this in one command:

wp media import images_folder/*

Regenerating Images

You’ll need to regenerate the thumbnails of the images once you set a new image size in the development process. Of course, you can use a plugin to perform this such as regenerate-thumbnails but with WP-CLI you can do it quickly and simply in one command:

wp media regenerate

There are countless options for this command since you can chain several commands and choose which images to perform the action on. For example, to perform the action on the featured images of posts in a specific category, you can use the following command:

wp media regenerate $(wp eval 'foreach( get_posts(array("category" => 2,"fields" => "ids")) as $id ) { echo get_post_thumbnail_id($id). " "; }')

Database Operations

When talking about advanced management of WordPress via the command line, database operations are always taken into account. WP-CLI provides tools for these tasks. For example, a simple query can be performed by:

wp db query "SELECT id FROM wp_users;"

In addition, operations such as import, export, and optimization of the database can be performed using the commands:

wp db export
wp db import backup.sql
wp db optimize

In the export operation, you can also use a script or through a cron job to ensure that the database is backed up automatically and on a schedule of your choice.


Search & Replace

Building a WordPress site in a local or development environment and transferring it to an online server upon completion is an action many of us have performed frequently. Copying files and importing the database are the easy parts. Replacing old URLs with new ones in the database, however, is a tricky operation because these URLs also exist in serialized data, which a regular search and replace will not recognize.

WP-CLI helps you perform this operation. The search-replace command replaces the old URLs with new ones in all database fields including those containing serialized data.

wp search-replace 'dev.example.com' 'www.example.com'

If you want to know the number of URLs you are looking for in the database, you can use the previous command and add the dry-run– parameter:

wp search-replace --dry-run 'dev.example.com' 'www.example.com'

The result will be something like this:

+---------------------+-----------------------+--------------+------+
| Table               | Column                | Replacements | Type |
+---------------------+-----------------------+--------------+------+
| wpcli_options       | option_value          | 2            | PHP  |
| wpcli_posts         | post_content          | 1            | SQL  |
| wpcli_posts         | guid                  | 28           | SQL  |
+---------------------+-----------------------+--------------+------+

In Conclusion

If you have read this guide, you should have a general idea of the capabilities of WP-CLI. Of course, there are many more commands and built-in tools not mentioned in this guide. You can read more and get additional information on the official site.

I hope this guide helps you streamline your work (and mine) the next time we go to create a WordPress site… Good luck! 🙂

(Full disclosure – this article is based on the following post here)

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development