Hong Manh's BlogHong Manh's Blog Sharing Technology Knowledge

How To Install CLI For WordPress

The WP-CLI is a very diverse toolset that can be installed at the command line for managing WordPress websites. If you’re familiar with using such tools at the command line level then the information to follow should be relatively easy. However, if this is not something you’ve done before then we hope this helps you learn.


A command line interface can save so much time, automate tasks, and make mass management of sites much easier for any software, and WordPress is no exception. If you have any older template, or one from a hosting provider other than Knownhost that lacks wp-cli, you can use the following instructions to install it. To install this CLI for WordPress, start by grabbing the package from Github:

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

Check the Phar file to verify that it’s working before proceeding further:

  php wp-cli.phar --info

At this point, you should have the following output in your terminal:

Most WP-CLI guides you encounter will use WP-CLi via the ‘wp’ command, so it is best to stay consistent with this common practice. Let’s configure this with the following commands:

  chmod +x wp-cli.phar
  mv wp-cli.phar /usr/local/bin/wp

To confirm that WP-CLI was installed successfully, run wp –info again:

  wp --info

You should see the following output after these steps:

Using as Root

Don’t run WP-CLi as root when working with your applications! This is a security issue, and WP-CLI warns against this:

Additional Directions for CageFS users

Now, as you have installed wp-cli, let’s add it to the CageFS so that users could access it

Create the file /etc/cagefs/conf.d/wpcli.cfg and add the following content to it:


Update CageFS

  cagefsctl --force-update

To test, run WP-CLi as a CageFS user (replace $username below with a CageFS user):

  su -c "wp --info" $username

Managing WordPress with WP-CLI

To use WP-CLI, su to your WordPress user first (they will need shell privileges), change into the directory containing the WordPress installation, and issue the desired commands. There is so much you can do with WP-CLI, such as manage plugins, make database backups, update WordPress core, verify WordPress core files against the current repository (useful for identifying malicious code injections in WordPress core files), manage themes, create posts, and more!

Common tasks/commands are as follows:

wp cli version Show WP-CLI version
wp help list all commands
wp help <command> <required_paramater> Get help on a particular command, e.g., wp maintenance-mode status
wp core download Download WordPress
wp core install install WordPress (you can configure basic wp_options by passing url, site_title, admin_user, and admin_email in the command parameters)
wp core update update WordPress core
wp core version show WordPress core version
wp core config Configure the wp-config.php file by passing configuration information in parameters to this command, such as database information (which you could then use ‘wp db create’ to create)
wp core verify-checksums verify WordPress core checksums
wp plugin list list installed plugins (a project in underway to allow verification of themes as well)
wp plugin install wordfence –activate install and activate the Wordfence plugin
wp plugin search wordfence prints plugin information from repository so that you know what slug to use with ‘wp plugin install $plugin_slug’
wp plugin deactivate wordfence deactivates plugin wordfence (useful if you are blocked via wp-admin from accessing your site)
wp plugin deactivate –all deactivates all plugin (useful for troubleshooting white/blank page errors)
wp plugin update wordfence update the wordfence plugin
wp plugin verify-checksums –all verify all plugin checksums
wp theme list list installed themes
wp theme install twentyseventeen –activate install and activate twentyseventeen theme
wp theme delete twentyseventeen delete twentyseventeen theme
wp search-replace oldstring newstring search the database for oldstring and replace with newstring (unserializes and researializes strings that are stored in a serialized format)
wp db size –tables shows the size of all tables inside the database (useful for helping you determie if you need to clean up post revisions, transients, unused plugun data, etc)
wp db export make a database backup sql file
wp db import dbprefix_dbname.sql import the backup file for dbprefix_dbname from dbprefix_dbname.sql file
wp db check check database using mysqlcheck
wp db repair repair crashed database
wp db optimize optimize database
wp db query “SELECT * FROM wp_options” run custom query in quotes against the database
wp user list –all list all users
wp user list –role=administrator lists administrators
wp user reset-password admin editor resets password for users admin and editor
wp user update 100 –user_pass=newuserpass update a user information for user ID 100, specifically password in this example
wp rewrite flush flush rewrite rules
wp rewrite structure ‘/%postname%’ update permalinks as defined in quotes
wp cron event list list all wp_cron events
wp maintenance mode status show maintenance mode status
wp maintenance mode activate activate maintenance mode
wp maintenance mode deactivate deactivate maintenance mode
wp config get shows the configuration via wp-config.php
wp config list WP_DEBUG show WP_DEBUG mode status from wp-config.php
wp config set WP_DEBUG true enable WP_DEBUG mode
wp config set WP_DEBUG false disable WP_DEBUG mode
wp option update home ‘https://homeurl.com update wp_options database option to the URL specified
wp option update siteurl ‘https://siteurl.com update wp_options database option to the URL specified
wp transient delete –all delete all transient data
wp post delete 33 delete post number 33
wp post create –prompt an interactive prompt to create a new post from the command line
wp post create –post_type=page –page_status=publish –post_title=’Contact Us’ –post-content=’PHONE: 555-555-5555′ Creates a new ‘Contact Us’ page with contact phone number
wp option list –autoload=on –format=total_bytes get the total size of all autoload options from the database
wp comment delete $(wp comment list –status=spam –format=ids) delete spam comments

Here is a quick overview of the WP-CLi commands accessible to you through WP-CLI via WP-CLI Commands :

Command Description
wp admin Open /wp-admin/ in a browser.
wp cache Adds, removes, fetches, and flushes the WP Object Cache object.
wp cap Adds, removes, and lists capabilities of a user role.
wp cli Review current WP-CLI info, check for updates, or see defined aliases.
wp comment Creates, updates, deletes, and moderates comments.
wp config Generates and reads the wp-config.php file.
wp core Downloads, installs, updates, and manages a WordPress installation.
wp cron Tests, runs, and deletes WP-Cron events; manages WP-Cron schedules.
wp db Performs basic database operations using credentials stored in wp-config.php.
wp dist-archive Create a distribution archive based on a project’s .distignore file.
wp embed Inspects oEmbed providers, clears embed cache, and more.
wp eval Executes arbitrary PHP code.
wp eval-file Loads and executes a PHP file.
wp export Exports WordPress content to a WXR file.
wp find Find WordPress installations on the filesystem.
wp help Get help on WP-CLI, or on a specific command.
wp i18n Provides internationalization tools for WordPress projects.
wp import Imports content from a given WXR file.
wp language Installs, activates, and manages language packs.
wp maintenance-mode Activates, deactivates or checks the status of the maintenance mode of a site.
wp media Imports files as attachments, regenerates thumbnails, or lists registered image sizes.
wp menu Lists, creates, assigns, and deletes the active theme’s navigation menus.
wp network Perform network-wide operations.
wp option Retrieves and sets site options, including plugin and WordPress settings.
wp package Lists, installs, and removes WP-CLI packages.
wp plugin Manages plugins, including installs, activations, and updates.
wp post Manages posts, content, and meta.
wp post-type Retrieves details on the site’s registered post types.
wp profile Profiles code/file/hook/load process execution depending on the arguments
wp rewrite Lists or flushes the site’s rewrite rules, updates the permalink structure.
wp role Manages user roles, including creating new roles and resetting to defaults.
wp scaffold Generates code for post types, taxonomies, plugins, child themes, etc.
wp search-replace Searches/replaces strings in the database.
wp server Launches PHP’s built-in web server for a specific WordPress installation.
wp shell Opens an interactive PHP console for running and testing PHP code.
wp sidebar Lists registered sidebars.
wp site Creates, deletes, empties, moderates, and lists one or more sites on a multisite installation.
wp super-admin Lists, adds, or removes super admin users on a multisite installation.
wp taxonomy Retrieves information about registered taxonomies.
wp term Manages taxonomy terms and term meta, with create, delete, and list commands.
wp theme Manages themes, including installs, activations, and updates.
wp transient Adds, gets, and deletes entries in the WordPress Transient Cache.
wp user Manages users, along with their roles, capabilities, and meta.
wp widget Manages widgets, including adding and moving them within sidebars.

Managing WordPress Plugins with WP-CLI

You may even find your favorite plugins support WP-CLI. Some examples are given below.


One common example of this you may find useful is LSCache management via WP-CLI. A few of the more popular commands for the LSCache plugin are below:

wp lscache-admin get_options view available options
wp lscache-admin set_option option_name value change a particular option to a particular value
wp lscache-purge all purge all cache for the installation


Here are some of the options available for another popular favorite, Updraft.

wp updraftplus backup take a backup using the default options saved in your settings (outputs a job_id)
wp updraftplus restore <nonce> restore backup with specified nonce (unique identifier for the backup)
wp updraftplus existing_backups display existing backups
wp updraftplus get_latest_full_backup get the latest full backup job_id
wp updraftplus backup_progress <Job ID> displays backup progress by job_id


Below you will find many of the options available to WP-Optimize.

wp optimize optimizations list available optimizations
wp optimize do-optimization –optimization-id=optimizetables optimize tables
wp optimize do-optimization –optimization-id=revisions clean post revisions
wp optimize do-optimization –optimization-id=trash clean trash posts
wp optimize do-optimization –optimization-id=spam remove spam comments
wp optimize do-optimization –optimization-id=unapproved remove unapproved comments
wp optimize do-optimization –optimization-id=attachments remove orphaned attachments
wp optimize do-optimization –optimization-id=transient remove expired transients
wp optimize do-optimization –optimization-id=pingbacks remove pingbacks
wp optimize do-optimization –optimization-id=trackbacks remove trackbacks
wp optimize do-optimization –optimization-id=postmeta clean post meta data
wp optimize do-optimization –optimization-id=commentmeta clean comment meta data

Many other plugins offer WP-CLI integration, such as JetpackRedis-CachePHP Compatibility CheckerGoogle Sitemap GeneratoriThemes SecurityBackupBuddy, and many, many more! You can even add WP-CLI support to your own plugin.

WP-CLI Addons

There are some popular addons for WP-CLI that many find useful. These are WP Doctor and WP Profile. WP Profile is helpful for profiling a site to determine what is slowing it down and for finding those bottlenecks. WP DOCTOR is especially useful for exploited sites as it contains the following helpful functions:

wp doctor check –all runs all checks
wp doctor check file-eval searches for the eval\(*base64_decod\).* regex (common in malware)
wp doctor check core-update verifies if core is up-to-date
wp doctor check plugin-update verifies is plugins are up-to-date
wp doctor check theme-update verifies is themes are up-to-date
wp doctor check php-in-upload checks for php files in the uploads directory (common in exploits)

WP Doctor also offers the following functions to assist with optimization:

wp doctor check autoload-options-size gives the size of autoload data in the wp_options table
wp doctor check constant-savequeries-falsy checks whether this is off or on as it is resource-intensive and should be disabled in a production environment for optimal performance
wp doctor check constant-wp-debug-falsy checks the status of WP-DEBUG, which should be off in production
wp doctor check cron-counts checks that the number of crons is a sane value and issues a warning if not
wp doctor check cron-duplicates checks for duplicated crons
wp doctor check plugin-active-count checks for a large number of unused, installed plugins that can be removed to improve performance

WP Doctor can be downloaded here: wp-cli Doctor Command

WP Doctor installation is as follows (you may need to also enable allow_url_fopen):

You would su into the user via ssh that you wish to install this plugin into — it’s done per account and is not a global install.

wp package install git@github.com:wp-cli/doctor-command.git

The output should resemble the following:

WP Profile allows one to break WordPress loading into three stages and profile how long each stage takes, and further break down each stage into its components so that one may track and locate bottlenecks in thier site’s performance. The three stages are as follows:

bootstrap loading plugins and the main theme, and firing the init hook
main_query transforming the request (the requested path) into the primary WP_Query
template determining which theme template to render based on the main query and then rendering it
wp profile stage –fields=stage,time,cache_ratio gives and overview of each stage

Using the example from the project’s Github page wp-cli profile command, here is the output:

  | stage      | time    | cache_ratio |
  | bootstrap  | 0.7994s | 93.21%      |
  | main_query | 0.0123s | 94.29%      |
  | template   | 0.792s  | 91.23%      |
  | total (3)  | 1.6037s | 92.91%      |

You can then further profile each stage with `wp profile stage <stage>` like so (example also via the Github page for the project):

  wp profile stage bootstrap --fields=hook,time,cache_ratio --spotlight
  | hook                     | time    | cache_ratio |
  | muplugins_loaded:before  | 0.2335s | 40%         |
  | muplugins_loaded         | 0.0007s | 50%         |
  | plugins_loaded:before    | 0.2792s | 77.63%      |
  | plugins_loaded           | 0.1502s | 100%        |
  | after_setup_theme:before | 0.068s  | 100%        |
  | init                     | 0.2643s | 96.88%      |
  | wp_loaded:after          | 0.0377s |             |
  | total (7)                | 1.0335s | 77.42%      |

WP Profile installation is as follows (you may need to also enable allow_url_fopen):

You would su into the user via ssh that you wish to install this plugin into — it’s done per account and is not a global install.

wp package install git@github.com:wp-cli/profile-command.git

Extending WP-CLI

WP-CLI is even extendable, allowing one to write and add one’s own commands. More information can be found here:

WP_CLI::add_command() Commands Cookbook


You can take this as far as you’d like to completely automate WordPress hosting by setting WP-CLI commands in sequence in a bash script to completely install and configure WordPress installations with your chosen plugins and themes. You can even attach these to post-account creation hooks in your panel so that these scripts are called automatically upon account creation. To take this to another level, you can further automate account creation in both DirectAdmin and cPanel as they both have extensive APIs that support this. The possibilities are endless and the hosting industry is more automated than ever, thanks to amazing tools such as WP-CLI.

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments

Press ESC to close

Would love your thoughts, please comment.x