Atomic Smash homepage splash

Working with the WordPress Command Line Interface (WP CLI)

Words by Adam WardJuly 14, 2017

In this post we will run through…

  • What is the WordPress Command Line Interface (WP CLI)?
  • How to set it up
  • Working with the default commands and functions
  • How to install packages
  • Creating our first function

What is the WP CLI?

The WordPress Command Line Interface (CLI) was introduce in version 3.7, with the intention of making a library of CLI commands to enable users to perform every function already possible in the WordPress admin interface.

So, why use it then?

The WP CLI is a few years old now, but even though I develop with WordPress daily, previously I hadn’t given enough time to learn about it properly and I wasn’t too sure how it could actually benefit me.

A single WP CLI command could be the equivalent to 20 plus clicks and a whole lot of browser refreshing, so in terms of speed, it really is a lot quicker to perform general tasks. The real power of the WP CLI is how easy it is to extend and create your own functions, which will not only save you a lot of time but enable you to carry out tasks not possible just using the admin interface.

Hmmm, give me some examples!

If you wanted to return all of the user ID’s and names quickly, you can run the following command

$ wp user list

which returns a list like this, in your terminal window…

+----+------------+--------------+----------------------+-----------------------+---------------+
| ID | user_login | display_name | user_email           | user_registered       | roles         |
+----+------------+--------------+----------------------+-----------------------+---------------+
| 40 | agrahami   | agrahami     | agrahami@upenn.edu   | 2017-07-10 13:59:15   | subscriber    |
| 38 | amitchellg | amitchellg   | amitchellg@cdc.gov   | 2017-07-10 13:59:15   | subscriber    |
| 27 | areid5     | areid5       | areid5@phoca.cz      | 2017-07-10 13:59:15   | subscriber    |
| 32 | bbutlera   | bbutlera     | bbutlera@fc2.com     | 2017-07-10 13:59:15   | subscriber    |
| 36 | cwatsone   | cwatsone     | cwatsone@ted.com     | 2017-07-10 13:59:15   | subscriber    |
| 37 | dsullivanf | dsullivanf   | dsullivanf@tripadvis | 2017-07-10 13:59:15   | subscriber    |

That command took about 5 seconds to write out and process, whereas the equivalent in the admin interface would take much longer.

Another example, would be for debugging purposes, sometimes it’s necessary to activate and deactivate plugins to isolate an error. This obviously can be done in the admin interface but it feels so much faster when doing it in the WP CLI. For example if you split a terminal window, one with the list of plugins on the site…

$ wp plugin list
+------------------------------------+----------+-----------+---------+
| name                               | status   | update    | version |
+------------------------------------+----------+-----------+---------+
| advanced-custom-fields-pro         | active   | none      | 5.5.14  |
| simple-page-ordering               | inactive | none      | 2.2.4   |
| timber-library                     | active   | available | 1.3.2   |
| user-switching                     | inactive | none      | 1.0.9   |
| wp-usergen-cli-master              | active   | none      | 1.0.0   |
| wordpress-seo                      | inactive | available | 4.9     |
+------------------------------------+----------+-----------+---------+

and use the other pane to deactivate and active plugins, at lightening speed!

$ wp plugin deactivate advanced-custom-fields-pro

And if the problem still exists on the site then you can activate it again…

$  wp plugin activate advanced-custom-fields-pro

Setting up

The installation instructions from the main wp-cli.org website are very clear and good to follow – http://wp-cli.org/#installing

After installing, if you head to your project in terminal and run $ wp you will notice a list of options are returned. Scroll down through these options and try experimenting with them. To cancel out of this mode, sometimes it’s necessary to press Ctrl + C a couple of times. To run one of the default functions, we need to append one of them on to the $ wp command i.e. $ wp user this will then show you another list of options/functions. Next lets run $ wp user list this will return a list of all the users on your site.

Common installation issues

If using MAMP and you’re getting an error when running wp – You might need to create a sym link between MAMP and the CLI so they are both using the same path and version of PHP. This link has a fix for the most common MAMP/WP-CLI issues –
https://indigotree.co.uk/getting-wp-cli-work-mamp/

If you are still encountering issues try changing your wp-config.php file line define(‘DB_HOST’ from –

define('DB_HOST', ‘localhost’);

// change to 

define('DB_HOST', '127.0.0.1:8889');

Using Packages

The WP CLI was built in a very easy to extend way, which means not only can you create your own functions but you can use other packages made by other Developers. A list of packages can be found here – http://wp-cli.org/package-index/ . Most of these packages can be installed directly using

$ wp package install <package-name>

or by downloading the zip file and installing them as a plugin from their repository links (sometimes this is the recommended way). Lets install this package https://github.com/alessandrotesoro/wp-usergen-cli . This package is very useful for creating lots of fake users.

Install the plugin either by using the CLI command –

$ wp package install alessandrotesoro/wp-usergen-cli

Or if you’re having issues doing it that way just download the plugin zip from the repo and install as a plugin like normal by going to the plugin page in the WP backend and clicking ‘Add new’ and uploading the zip.

Now if we run $ wp you will notice a new usergen function towards the bottom of the available wp functions. If you run $ wp usergen the function will return 2 possible functions and examples `generate ` and `purge`. Lets test it out – first of all run $ wp user list this will return your current users then run $ wp usergen generate 50, now if we run $ wp use list again, you’ll notice we have another 50 users, complete with names, logins and email addresses.

Creating our own function

Along with very useful default commands and packages, the WP CLI is easily extendable for you to build your on functions too! Next, we will create out own function for get all the users, that are subscribers, from our website and putting it in to a CSV file. I’ve had to do this numerous times for clients and although there are other WP CLI functions/plugins to do this, but doing it yourself makes it much easier if you need to adjust it in the future or if you have to create multiple variations.

I believe it’s good practice to keep your cli functions in their own file and include it your functions.php file, but for now lets just place it at the bottom of the functions.php file.

// This line is to check if the WP CLI is running on not
if ( defined( 'WP_CLI' ) && WP_CLI ) {
    // Create our new class name which will extend the WP_CLI_Command
    class Example_CLI extends WP_CLI_Command {
        // Create our function
        public function export_users_to_csv() {

            echo "Our CLI function is working!"; 
	  }


    }
    // Add our command to the new class
    WP_CLI::add_command( 'example', 'Example_CLI' );

} 

This sets up our basic function. If you type $ wp now you will notice an `example` function in the list of commands. Next lets try the $ wp example now your’ll see the option our CLI class has, which is the `export_users_to_csv` function, lets now run that $ wp example export_users_to_csv this should return “Our CLI function is working!” in your terminal window.

Now we have the function running correctly, lets build up the rest of the function.

// This line is to check if the WP CLI is running on not
if ( defined( 'WP_CLI' ) && WP_CLI ) {
    // Create our new class name which will extend the WP_CLI_Command
    class Example_CLI extends WP_CLI_Command {
        // Create our function
        public function export_users_to_csv() {

            // Get all 'subscribers'
            $user_args = array('role' => 'subscriber');
    		$get_users = get_users($user_args);

            // Add column headings to our results array
    		$file_data[] = array('User ID', 'First Name', 'Last Name', 'Email');

            // Loop through and add each user to the array
    		foreach ($get_users as $user) {
                $file_data[] = array($user->ID, $user->first_name, $user->last_name, $user->user_email);
            }

            // Check if file name exists already
            $file_name = 'user-file.csv';

            if ( file_exists( $file_name ) ) {
    			WP_CLI::warning(WP_CLI::colorize( "%r File alredy exists %n " ));
                WP_CLI::confirm( "Save and overwrite?" );
    		}

            // Create the csv file and add the array to it
    		$fp = fopen($file_name, 'w+');

    		foreach ($file_data as $fields) {
    			fputcsv($fp, $fields);
    		}

    		fclose($fp);

        	WP_CLI::success(WP_CLI::colorize( "%g Users File created %n " ));

    	}
    }
    // Add our command to the new class
    WP_CLI::add_command( 'example', 'Example_CLI' );

}

So that’s it. We have created our first WP CLI function that gets all subscribers from your website and adds them to a CSV file.

Let me run through a couple of the extra bits in the code above. When we check to see if the file already exists in our project we run a “WP_CLI::warning” this informs the user there is already a file with this name and then we use the “WP_CLI::confirm” function, which will prompt the user to respond with either yes or no. You will also notice that we are using the “WP_CLI::colorize” function, which enable you to colour the text in the Terminal, which helps to make the prompts stand out more and just looks a little nicer!

You can find out more about the available functions here – https://make.wordpress.org/cli/handbook/internal-api/

I hope this post has been useful for you and cleared up any unknowns you might have had previously. There’s so much you can do with the WP CLI, it’s really worth exploring more and trying to create your own functions to cut down on mundane tasks you find yourself repeating.

Profile picture of Adam Ward

Adam WardDeveloper

Adam is an expert in WordPress development and CRM integrations. His ability to craft WordPress to a users needs makes our websites easier to use.

Go back to top

Keep up to date with Atomic news