Hosting Question? Find the Solution -

KNOWNHOST KNOWLEDGE BASE

Browse our Guides, Articles, and How-To's

How To Install CLI For WordPress

Category: WordPress
Tags: # # # # # #

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.

WP-CLI is essential for WordPress hosting, and is included in cPanel by default at the following path:

  /usr/local/cpanel/3rdparty/bin/wp

It can be found on our DirectAdmin templates at the following path:

  /usr/local/bin/wp

Installation

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:

  [wpcli]
  comment=WP-CLI
  paths=/usr/local/bin/wp

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 versionShow WP-CLI version
wp helplist all commands
wp help <command> <required_paramater>Get help on a particular command, e.g., wp maintenance-mode status
wp core downloadDownload WordPress
wp core installinstall WordPress (you can configure basic wp_options by passing url, site_title, admin_user, and admin_email in the command parameters)
wp core updateupdate WordPress core
wp core versionshow WordPress core version
wp core configConfigure 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-checksumsverify WordPress core checksums
wp plugin listlist installed plugins (a project in underway to allow verification of themes as well)
wp plugin install wordfence –activateinstall and activate the Wordfence plugin
wp plugin search wordfenceprints plugin information from repository so that you know what slug to use with ‘wp plugin install $plugin_slug’
wp plugin deactivate wordfencedeactivates plugin wordfence (useful if you are blocked via wp-admin from accessing your site)
wp plugin deactivate –alldeactivates all plugin (useful for troubleshooting white/blank page errors)
wp plugin update wordfenceupdate the wordfence plugin
wp plugin verify-checksums –allverify all plugin checksums
wp theme listlist installed themes
wp theme install twentyseventeen –activateinstall and activate twentyseventeen theme
wp theme delete twentyseventeendelete twentyseventeen theme
wp search-replace oldstring newstringsearch the database for oldstring and replace with newstring (unserializes and researializes strings that are stored in a serialized format)
wp db size –tablesshows 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 exportmake a database backup sql file
wp db import dbprefix_dbname.sqlimport the backup file for dbprefix_dbname from dbprefix_dbname.sql file
wp db checkcheck database using mysqlcheck
wp db repairrepair crashed database
wp db optimizeoptimize database
wp db query “SELECT * FROM wp_options”run custom query in quotes against the database
wp user list –alllist all users
wp user list –role=administratorlists administrators
wp user reset-password admin editorresets password for users admin and editor
wp user update 100 –user_pass=newuserpassupdate a user information for user ID 100, specifically password in this example
wp rewrite flushflush rewrite rules
wp rewrite structure ‘/%postname%’update permalinks as defined in quotes
wp cron event listlist all wp_cron events
wp maintenance mode statusshow maintenance mode status
wp maintenance mode activateactivate maintenance mode
wp maintenance mode deactivatedeactivate maintenance mode
wp config getshows the configuration via wp-config.php
wp config list WP_DEBUGshow WP_DEBUG mode status from wp-config.php
wp config set WP_DEBUG trueenable WP_DEBUG mode
wp config set WP_DEBUG falsedisable WP_DEBUG mode
wp option update home ‘https://homeurl.comupdate wp_options database option to the URL specified
wp option update siteurl ‘https://siteurl.comupdate wp_options database option to the URL specified
wp transient delete –alldelete all transient data
wp post delete 33delete post number 33
wp post create –promptan 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_bytesget 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 1)WP-CLI Commands :

CommandDescription
wp adminOpen /wp-admin/ in a browser.
wp cacheAdds, removes, fetches, and flushes the WP Object Cache object.
wp capAdds, removes, and lists capabilities of a user role.
wp cliReview current WP-CLI info, check for updates, or see defined aliases.
wp commentCreates, updates, deletes, and moderates comments.
wp configGenerates and reads the wp-config.php file.
wp coreDownloads, installs, updates, and manages a WordPress installation.
wp cronTests, runs, and deletes WP-Cron events; manages WP-Cron schedules.
wp dbPerforms basic database operations using credentials stored in wp-config.php.
wp dist-archiveCreate a distribution archive based on a project’s .distignore file.
wp embedInspects oEmbed providers, clears embed cache, and more.
wp evalExecutes arbitrary PHP code.
wp eval-fileLoads and executes a PHP file.
wp exportExports WordPress content to a WXR file.
wp findFind WordPress installations on the filesystem.
wp helpGet help on WP-CLI, or on a specific command.
wp i18nProvides internationalization tools for WordPress projects.
wp importImports content from a given WXR file.
wp languageInstalls, activates, and manages language packs.
wp maintenance-modeActivates, deactivates or checks the status of the maintenance mode of a site.
wp mediaImports files as attachments, regenerates thumbnails, or lists registered image sizes.
wp menuLists, creates, assigns, and deletes the active theme’s navigation menus.
wp networkPerform network-wide operations.
wp optionRetrieves and sets site options, including plugin and WordPress settings.
wp packageLists, installs, and removes WP-CLI packages.
wp pluginManages plugins, including installs, activations, and updates.
wp postManages posts, content, and meta.
wp post-typeRetrieves details on the site’s registered post types.
wp profileProfiles code/file/hook/load process execution depending on the arguments
wp rewriteLists or flushes the site’s rewrite rules, updates the permalink structure.
wp roleManages user roles, including creating new roles and resetting to defaults.
wp scaffoldGenerates code for post types, taxonomies, plugins, child themes, etc.
wp search-replaceSearches/replaces strings in the database.
wp serverLaunches PHP’s built-in web server for a specific WordPress installation.
wp shellOpens an interactive PHP console for running and testing PHP code.
wp sidebarLists registered sidebars.
wp siteCreates, deletes, empties, moderates, and lists one or more sites on a multisite installation.
wp super-adminLists, adds, or removes super admin users on a multisite installation.
wp taxonomyRetrieves information about registered taxonomies.
wp termManages taxonomy terms and term meta, with create, delete, and list commands.
wp themeManages themes, including installs, activations, and updates.
wp transientAdds, gets, and deletes entries in the WordPress Transient Cache.
wp userManages users, along with their roles, capabilities, and meta.
wp widgetManages 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.

LSCache

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_optionsview available options
wp lscache-admin set_option option_name valuechange a particular option to a particular value
wp lscache-purge allpurge all cache for the installation

Updraft

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

wp updraftplus backuptake 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_backupsdisplay existing backups
wp updraftplus get_latest_full_backupget the latest full backup job_id
wp updraftplus backup_progress <Job ID>displays backup progress by job_id

WP-Optimize

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

wp optimize optimizationslist available optimizations
wp optimize do-optimization –optimization-id=optimizetablesoptimize tables
wp optimize do-optimization –optimization-id=revisionsclean post revisions
wp optimize do-optimization –optimization-id=trashclean trash posts
wp optimize do-optimization –optimization-id=spamremove spam comments
wp optimize do-optimization –optimization-id=unapprovedremove unapproved comments
wp optimize do-optimization –optimization-id=attachmentsremove orphaned attachments
wp optimize do-optimization –optimization-id=transientremove expired transients
wp optimize do-optimization –optimization-id=pingbacksremove pingbacks
wp optimize do-optimization –optimization-id=trackbacksremove trackbacks
wp optimize do-optimization –optimization-id=postmetaclean post meta data
wp optimize do-optimization –optimization-id=commentmetaclean 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 –allruns all checks
wp doctor check file-evalsearches for the eval\(*base64_decod\).* regex (common in malware)
wp doctor check core-updateverifies if core is up-to-date
wp doctor check plugin-updateverifies is plugins are up-to-date
wp doctor check theme-updateverifies is themes are up-to-date
wp doctor check php-in-uploadchecks 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-sizegives the size of autoload data in the wp_options table
wp doctor check constant-savequeries-falsychecks 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-falsychecks the status of WP-DEBUG, which should be off in production
wp doctor check cron-countschecks that the number of crons is a sane value and issues a warning if not
wp doctor check cron-duplicateschecks for duplicated crons
wp doctor check plugin-active-countchecks 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):

  php -d memory_limit=512M /usr/local/cpanel/3rdparty/bin/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:

bootstraploading plugins and the main theme, and firing the init hook
main_querytransforming the request (the requested path) into the primary WP_Query
templatedetermining which theme template to render based on the main query and then rendering it
wp profile stage –fields=stage,time,cache_ratiogives 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):

  php -d memory_limit=512M /usr/local/cpanel/3rdparty/bin/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

The wp Command and PATH Specification in Linux

For those of you using cPanel, or a KnownHost DirectAdmin server, WP-CLi is already installed, but you must specify the full path:

Example:

  /usr/local/cpanel/3rdparty/bin/wp user list --all

If you want to use the command without the full path, either add it to your cPanel user’s PATH or create an alias.

To create an alias, run the following commands as the user:

  echo "alias wp='/usr/local/cpanel/3rdparty/bin/wp'" >> ~/.bashrc
  source ~/.bashrc

Alternatively, if you want all users on your cPanel users to have this alias, add the alias in a bash script under /etc/profile.d/ like so:

  echo "alias wp='/usr/local/cpanel/3rdparty/bin/wp'" >> /etc/profile.d/wp-cli_alias.sh
  chmod +x /etc/profile.d/wp-cli_alias.sh

Note: this should work fine if you log in directly to SSH as a cPanel user, however, if you su’d to the user, of if you did not log out and back in after making the changes, you may need to run the following command, which will source /etc/profile (which includes all files in /etc/profile.d/, such as the one we just made):

  source /etc/profile

For example:

Conclusion

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.