WordPress Tutorial

How to Install and Use WP-CLI to Manage WordPress Blog

Introduction

WP-CLI is a tool that gives you the ability to administrate your WordPress through a command line interface. You can execute standard functions, such as plugin installations, as well as commands that are not supported through the standard WordPress back-end.

The biggest benefit to WP-CLI is the amount of time it saves you when you’re installing, configuring or maintaining WordPress based websites. If you have multiple sites, you no longer need to log in to each one to take care of basic tasks and the WP-CLI commands can also be automated.

In this WordPress tutorial you will learn how install and use WP CLI to its full potential.

What you’ll need

Before you begin this guide, you’ll need the following:

  • Access to the command line interface

Step 1 – Installing WP-CLI

On Hostinger shared hosting WP-CLI is already installed. Thus, you only need to connect to your account via SSH in order to use it.

If you want to install WP-CLI on VPS or a local Linux system, follow the steps below:

  1. Download the WP-CLI tool from Github with the following command:
    curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
  2. Confirm that it has downloaded successfully with this command:
    php wp-cli.phar --info
  3. Now you need to set wp-cli.phar to be an executable file. Type:
    chmod +x wp-cli.phar
  4. To finalize the installation, move WP-CLI into its final location:
    sudo mv wp-cli.phar /usr/local/bin/wp

Now that WP-CLI is installed, you can start working with your WordPress content and files through the command line.

Step 2 – Understanding WP-CLI Commands

WP-CLI is a straightforward tool if you’re already familiar with a command line environment. You gain the ability to control your blog through commands, which is often faster than going into the WordPress administration panel and clicking through various options. You also have the opportunity to script commands for streamlined processes.

WP-CLI comes with quite a few inbuilt commands. And the list of available WP-CLI commands can be extended by installing plugins which support WP-CLI. You can see the list of WP-CLI plugins along with the commands here. Let’s take a look at a few basic WP-CLI commands:

The command below shows the WP-CLI version information:

wp --info

Example output:

PHP binary: /opt/alt/php70/usr/bin/php
PHP version:    7.0.16
php.ini used:   /opt/alt/php70/etc/php.ini
WP-CLI root dir:    phar://wp-cli.phar
WP-CLI packages dir:    
WP-CLI global config:   
WP-CLI project config:  
WP-CLI version: 1.1.0

The command needed in order to access the list of WP-CLI commands and help documentation:

wp help

Example output:

DESCRIPTION

  Manage WordPress through the command-line.

SYNOPSIS

  wp <command>

SUBCOMMANDS

  cache               Manage the object cache.
  cap                 Manage user capabilities.
  cli                 Manage WP-CLI itself.
  comment             Manage comments.
  core                Download, install, update and manage a WordPress install.
  cron                Manage WP-Cron events and schedules.
  db                  Perform basic database operations using credentials stored in wp-config.php     
  eval                Execute arbitrary PHP code.
  eval-file           Load and execute a PHP file.
   .....

To exit WP-CLI help page, press Q button on your keyword.

You can also see a separate help page for each WP-CLI command. For example, if you want to know more about comment command, type in:

wp help comment

Example output:

NAME

  wp comment

DESCRIPTION

  Manage comments.

SYNOPSIS

  wp comment <command>

SUBCOMMANDS

  approve        Approve a comment.
  count          Count comments, on whole blog or on a given post.
  create         Create a new comment.
  delete         Delete a comment.
  exists         Verify whether a comment exists.
  generate       Generate some number of new dummy comments.
  .....

As you can see from the example output, each WP-CLI command has a list of subcommands. For instance, to get the number of comments we can use the following subcommand:

wp comment count

And this is not the end, you can go down even further and see the help page for subcommand of a subcommand like this:

wp help comment count

Example output:

AME

  wp comment count

DESCRIPTION

  Count comments, on whole blog or on a given post.

SYNOPSIS

  wp comment count [<post-id>]

OPTIONS

  [<post-id>]
  The ID of the post to count comments in.
  .....

WP-CLI Commands Cheat Sheet

If it’s the first time you are using WP-CLI, this cheat sheet will be useful for you. It has all official WP-CLI commands along with examples and WP-CLI global parameters.

WP-CLI Commands Cheat Sheet

Step 3 – Using WP-CLI to Install WordPress

You can handle the complete WordPress installation process through WP-CLI. However, you do need to create a MySQL database for your blog before proceeding. At Hostinger, MySQL database can be created in Control Panel -> MySQL Databases section.

If you are using WP-CLI on VPS or a local system, follow these steps in order to create a new MySQL database:

  1. Log in to MySQL:
    mysql -u yourusername -p
  2. Make a database for your WordPress installation:
    create database wordpress;
  3. Set up the username and password for the database:
    grant all on wordpress.* to 'username' identified by 'yourpassword';
  4. Download the WordPress installation files:

Once MySQL database is ready, you can proceed with WordPress installation. First of all, you need to download the newest WordPress version. You can do this by executing:

wp core download

Example output:

Downloading WordPress 4.7.3 (en_US)...
md5 hash verified: 044729d30b720809f19e14ece49e119b
Success: WordPress downloaded.

IMPORTANT: make sure that you are in the correct directory before executing this command. Usually, all your website files should reside in public_html. You can see the directory in which you are in by executing the pwd command.

Once the download is complete, visit your website. You will see a standard WordPress installation form. Of course, you can go ahead and fill all required values by using a web browser. But since we have WP-CLI installed, it would be easier to do this in command line.

WordPress Installation Form

We will use the wp core command in order to add the MySQL database credentials to WordPress:

wp core config --dbname=wordpress --dbuser=user --dbpass=password --dbhost=localhost --dbprefix=wp_
  • dbname – Your MySQL database name.
  • dbuser – Your MySQL database username.
  • dbpass – Your MySQL user password.
  • dbhost – Your MySQL server hostname.
  • dbprefix – MySQL database table prefix. You can leave it wp_.As you can see the MySQL credentials can be passed using wp core config parameters. If you entered MySQL details correctly, WP-CLI will generate wp-config.php file:

Example output:

Success: Generated 'wp-config.php' file.

Now, if you will visit your WordPress site again, you will notice that it asks to enter a few additional details.

WordPress Installation Form Enter Site Details

We will use the same wp core command in order to add these details and complete the WordPress installation:

wp core install --url="yourdomain.com"  --title="Site Title" --admin_user="admin_username" --admin_password="admin_password" --admin_email="your@email.com"

Example output:

Success: WordPress installed successfully.

WordPress Installed with WP-CLI

Step 4 – Using WP-CLI to Install and Manage WordPress Themes

In this section, you will learn how to use WP-CLI in order to install WordPress themes. Let’s start by listing the already installed themes:

wp theme list

Example output:

+-----------------+----------+--------+---------+
| name            | status   | update | version |
+-----------------+----------+--------+---------+
| twentyfifteen   | inactive | none   | 1.7     |
| twentyseventeen | active   | none   | 1.1     |
| twentysixteen   | inactive | none   | 1.3     |
+-----------------+----------+--------+---------+

From the status, we can see that the current active theme is twentyseventeen. Let’s say we wan to activate twentyfifteen:

wp theme activate  twentyfifteen

Example output:

Success: Switched to 'Twenty Fifteen' theme.

You can even use WP-CLI to search for new themes in the official WordPress themes directory. Let’s search for a theme with bootstrap support:

wp theme search bootstrap

Example output:

Success: Showing 10 of 292 themes.
+---------------------+---------------------+--------+
| name                | slug                | rating |
+---------------------+---------------------+--------+
| edsBootstrap        | edsbootstrap        | 100    |
| Bootstrap Basic4    | bootstrap-basic4    | 0      |
| ultrabootstrap      | ultrabootstrap      | 100    |
| Bootstrap Four      | bootstrap-four      | 80     |
| Simple Bootstrap    | simple-bootstrap    | 60     |
| Bootstrap Canvas WP | bootstrap-canvas-wp | 92     |
| Flat Bootstrap      | flat-bootstrap      | 100    |
| Bootstrap Basic     | bootstrap-basic     | 100    |
| DevDmBootstrap3     | devdmbootstrap3     | 100    |
| Arouse              | arouse              | 0      |
+---------------------+---------------------+--------+

You cannot say much about a theme from its name only, but ultrabootstrap sounds great and has a rating of 100. In order to install and activate the theme use:

wp theme install ultrabootstrap --activate

Example output:

Installing ultrabootstrap (1.1.5)
Downloading install package from https://downloads.wordpress.org/theme/ultrabootstrap.1.1.5.zip...
Unpacking the package...
Installing the theme...
Theme installed successfully.
Activating 'ultrabootstrap'...
Success: Switched to 'ultrabootstrap' theme.
Success: Installed 1 of 1 themes.

This is how our WordPress looks with the new theme activated:

WordPress New Theme Activated with WP-CLI

You can also specify the path of a WordPress theme zip archive if you have it on your hosting account. This command also works with URLs.

Step 5 – Using WP-CLI to Install and Manage WordPress Plugins

Just like themes, plugins can be installed and managed by using WP-CLI. In order to list the already installed plugins use:

wp plugins list

Example output:

+---------+----------+--------+---------+
| name    | status   | update | version |
+---------+----------+--------+---------+
| akismet | inactive | none   | 3.3     |
| hello   | inactive | none   | 1.6     |
+---------+----------+--------+---------+

As you can see we don’t have many plugins. Let’s install a contact form plugin for our WordPress blog.

First, search the plugin directory for the contact form 7 plugin:

wp plugin search "contact form 7"

Example output:

Success: Showing 10 of 2514 plugins.
+--------------------------------------+---------------------------+--------+
| name                                 | slug                      | rating |
+--------------------------------------+---------------------------+--------+
| Contact Form 7                       | contact-form-7            | 92     |
| Contact Bank - Contact Forms Builder | contact-bank              | 86     |
| Contact Form                         | contact-forms-builder     | 90     |
| Contact Form                         | contact-form-ready        | 96     |
| Contact Form                         | contact-form-add          | 76     |
| Contact Form                         | powr-contact-form         | 100    |
| Contact Form                         | better-contact-form       | 100    |
| Contact Form                         | contact-form-master       | 96     |
| Contact Form                         | contact-form-maker        | 88     |
| Contact Form by Supsystic            | contact-form-by-supsystic | 92     |
+--------------------------------------+---------------------------+--------+

Contact Form 7 is the first one on the list. We want to install and activate it, since it’s a great plugin for creating lightweight contact forms:

wp plugin install contact-form-7 --activate

Example output:

Installing Contact Form 7 (4.7)
Downloading install package from https://downloads.wordpress.org/plugin/contact-form-7.4.7.zip...
Unpacking the package...
Installing the plugin...
Plugin installed successfully.
Activating 'contact-form-7'...
Plugin 'contact-form-7' activated.
Success: Installed 1 of 1 plugins.

Same as themes, plugins can be installed from zip archive and URL.

In order to delete a plugin change install to delete:

wp plugin delete contact-form-7

Example output:

Deleted 'contact-form-7' plugin.
Success: Deleted 1 of 1 plugins.

Step 6 – Using WP-CLI to Update WordPress

Updating WordPress with WP-CLI is a two-step process, as you need to update WordPress files and the database in order to complete this process.

Start by updating WordPress core files:

wp core update

Example output:

Updating to version 4.7.3 (en_US)...
Downloading update from https://downloads.wordpress.org/release/wordpress-4.7.3-new-bundled.zip...
Unpacking the update...
Cleaning up files...
Success: WordPress updated successfully.

Run the command below to check and if its necessary to update the database to the required version:

wp core update-db

Example output:

Success: WordPress database already at latest db version 38590.

To update WordPress themes and plugins with WP-CLI change core to theme or plugin. –all parameter is used to update all installed themes/plugins, but you can change it to a specific theme/plugin name if needed:

For themes:

wp theme update --all

For plugins:

wp plugin update --all

Step 7 – Using WP-CLI to Manage Content

Posts

WP-CLI provides several ways to manage your content through the command line. Yes, it may not be very comfortable to write posts in terminal, but for the sake of learning let’s see how to create and manage content with WP-CLI.

To see the list of all posts use:

wp post list

Example output:

+----+--------------+-------------+---------------------+-------------+
| ID | post_title   | post_name   | post_date           | post_status |
+----+--------------+-------------+---------------------+-------------+
| 1  | Hello world! | hello-world | 2017-03-15 11:11:00 | publish     |
+----+--------------+-------------+---------------------+-------------+

As you can see we only have one post – Hello world! . The ID of this post is 1. We can delete it with:

wp post delete 1

Example output:

Success: Trashed post 1.

To create a new post, use:

wp post create --post_status=publish --post_title="This Post Was Created With WP-CLI" --edit

This command will open vim text editor. Input the content and exit vim by pressing the ESC button, entering :wq and pressing ENTER.

WP-CLI Create Post

It’s also possible to create a new post and import post content directly from the .txt file:

wp post create ./post.txt --post_title='Sample Post' --post_status=publish

Apart from creating posts, with WP-CLI you can simply generate them. This feature is useful if you want to test how your WordPress site will work with a lot of posts. To auto generate 50 posts use:

wp post generate --count=50

Media

With WP-CLI you can automate image import process. Let’s say we want to import all images from folder images_for_site. We can achieve this by using a single command:

wp media import images_for_site/*

Step 9 – Using WP-CLI To Export/Import WordPress

With WP-CLI you can easily export or import contents from one WordPress installation to another. The following command will export posts, terms, authors, comments, and attachments to an XML file:

wp export

Example output:

Writing to file /home/u694443746/public_html/hostingertutorials.wordpress.2017-03-16.000.xml
Success: All done with export.

Let’s say we want to import the same XML file to another WordPress instance. First of all, we need to install wp-importer plugin:

wp plugin install wordpress-importer --activate

Once the installation is complete, we can proceed with the import. We will create a new author by using the –authors parameter:

wp import hostingertutorials.wordpress.2017-03-16.000.xml --authors=create

Example output:

<p>All done. <a href="http://hostinger-tutorials.com/wp-admin/">Have fun!</a></p><p>Remember to update the passwords and roles of imported users.</p>
Success: Finished importing from 'hostingertutorials.wordpress.2017-03-16.000.xml' file.

Step 10 – Using WP-CLI to Manage Database

You can run normal SQL queries with wp db query command. For example, in order to see all registered WordPress users use:

wp db query "SELECT user_login,ID FROM wp_users;"

Example output:

+------------+----+
| user_login | ID |
+------------+----+
| user       |  1 |
+------------+----+

You can run other useful operations like export. It will generate an SQL dump file of your WordPress database:

wp db export

Example output:

Success: Exported to 'u694443746_dapyz-a0d3f2a.sql'.

To import an SQL file into WordPress database, use:

wp db import file.sql

Example output:

Success: Imported from 'file.sql'.

Step 11 – Using WP-CLI to Search and Replace

If you have ever moved WordPress from local development or staging server to regular hosting, you know how useful search and replace can be. Of course, it can be done by using an SQL query or a plugin, but with WP-CLI search and replace can be performed with a single command. Let’s say we have changed our domain name from hostigner-tutorials.com to hostinger-tutorials.net and we need to update all URLs in our WordPress database.

It’s always recommended to make a ‘dry run’ before performing the actual search and replace. It will show how many instances would be changed:

wp search-replace --dry-run 'hostinger-tutorials.com' 'hostinger-tutorials.net'

Example output:

Success: 1008 replacements to be made.

Now, in order to perform the actual search and replace with WP-CLI, remove the –dry-run parameter:

wp search-replace 'hostinger-tutorials.com' 'hostinger-tutorials.net'

Example output:

Success: Made 1008 replacements.

Conclusion

Outside of these basic commands, WP-CLI can be extended through third-party and advanced commands. Working with WordPress is much more streamlined when you no longer need to click through each section in the administration panel. If you work with multiple WordPress sites, you will improve your productivity. This tutorial gives you the foundation you need in order to handle most routine WP-CLI tasks and functions.

About the author

Domantas G.

Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.

Add Comment

Click here to post a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

[href]
[href]
More in WordPress Tutorial
How to Fix Fatal Error: Maximum Execution Time Exceeded Error in WordPress

Close