At some point every WordPress site owner meets a job that the dashboard handles badly. Updating forty plugins one click at a time across six client sites. Changing the domain after a migration, when the admin screen no longer loads. Running a stuck scheduled task, or creating an administrator account when you are locked out. Importing a database that is far too big for a web form. Each of these takes seconds with WP-CLI, the official command-line interface for WordPress, and each is slow, fragile or impossible in a browser.
The single most important idea in this guide is that WP-CLI is not a different tool from WordPress. It is WordPress, loaded from a terminal instead of a web server. The same core, the same plugins, the same database and the same functions run, but with no browser, no web server timeout and no login screen in the way. That is why it is so powerful, and it is also why it is easy to misuse. Commands act immediately, on the real data, with the permissions of whoever typed them. A mistyped search and replace, or a delete with the wrong ID, has no recycle bin. Using WP-CLI well means learning a small set of commands, understanding what each one touches, and wrapping them in a few habits: back up first, preview when a preview exists, count before you delete, and always run as the right user in the right folder.
This guide is written for someone who has never opened a terminal on a WordPress server, and for the person who has pasted a few commands from forums and wants to know what they were actually doing. It starts with what happens under the hood when you run a command, then covers installing and verifying WP-CLI, reaching a shell over SSH, and why the user you run as matters. The core of the guide is 25 commands you will use again and again, grouped by job: core, plugins and themes, users, options and configuration, the database, search and replace, caches, cron, maintenance mode, posts and media. After that come aliases and configuration files so one terminal can manage several sites, scripting for repeatable jobs, and a troubleshooting section for the errors beginners meet most often.
A few honest boundaries. This is a general guide based on the official WP-CLI documentation, not a test report, and it contains no benchmark numbers. WP-CLI changes over time, so flags and defaults can move; the built-in help (wp help followed by a command) describes the version you actually have installed and is the final word when it disagrees with any article, this one included. Where an example uses a domain, a user name or a folder, it is a placeholder for you to replace with your own.
You do not need to learn programming. You need SSH access to a site, or a local copy to practise on, the patience to read what a command prints, and the discipline to try things on a staging copy before you touch production. Start with the commands that only read information, get comfortable with their output, and move on to commands that change things only when you can say, in one sentence, what each one will do and how you would undo it.
Key points
- WP-CLI loads the real WordPress from a terminal, so every command acts on live data with no undo; the habits around the commands matter as much as the syntax.
- Run it as the site’s own system user from the WordPress folder, check with wp –info which PHP and php.ini the command line uses, and avoid running as root.
- Twenty-five commands cover most daily work: core, plugins, themes, users, options, config, database, search-replace, caches, cron, maintenance mode, posts and media.
- Before any destructive command, export the database, then preview with a dry run or a count where one exists, and only then run it for real.
- Search-replace is the command that most often goes wrong; always dry-run it, skip the guid column and check the site afterwards.
- Aliases and wp-cli.yml let one terminal manage many sites over SSH, and scripts need full paths, explicit users and honest exit-code checks.
What WP-CLI is and what actually happens when you run a command
WP-CLI is the official command-line interface for WordPress. You type a short instruction such as wp plugin list into a terminal and WordPress does the work: it lists plugins, updates them, changes a setting, exports the database or creates a user, then prints the result and exits. Most things you can do in the dashboard that involve a button have a command, and a good deal that the dashboard cannot do at all has one too.
The useful mental model is that WP-CLI is WordPress without the web server. WP-CLI itself is a single PHP archive, usually called a phar, which you run with the PHP command-line program. When you press Enter it reads its configuration, works out where your WordPress folder is and, for most commands, loads WordPress properly: wp-config.php, core, your active plugins and your active theme. Then it runs your command inside that environment, talking to the same database your visitors use. The diagram shows the path.
That design has consequences worth learning on day one. Because plugins and themes load, a fatal error in one of them can stop WP-CLI too, which is why the global flags --skip-plugins and --skip-themes exist; they are your first rescue tool when a site shows a critical error. Because plugins load, commands that plugins register, such as a cache plugin’s own purge command, exist only while that plugin is active and loaded. Because no browser request is involved, there is no visitor to trigger scheduled tasks, no web server timeout to cut a long job short, and no logged-in user unless you ask for one. On a multisite network there is also no host name to tell WordPress which site you mean, so you pass --url.
A few commands deliberately do not load WordPress at all. Downloading core files, creating a wp-config.php file and verifying core checksums all work in an empty folder or on a site too broken to start, which makes them valuable in emergencies.
What does WP-CLI buy you? Speed on repetitive work, because one line replaces forty clicks. Reach, because it can handle databases and archives too large for a browser upload. Repeatability, because a command can be saved, reviewed, scheduled and run against ten sites in the same way. And precision, because output can be narrowed to exactly the fields you want. What it costs you is the safety net of a confirmation screen. Commands run with the privileges of whoever typed them and change real data at once, which is why the habits in later sections matter as much as the syntax. It does not replace the dashboard for writing content; it is a precise, scriptable tool for site administration.
What happens when you type a WP-CLI command
- Your shellYou type wp plugin list. The shell finds the wp file and starts the PHP command-line program.
- PHP command linePHP runs the WP-CLI archive using the command-line php.ini, which can differ from the web server one.
- Find WordPressWP-CLI looks in the current folder and its parents, or uses –path, to locate the install.
- Load WordPresswp-config.php, core, active plugins and theme load. No web request exists, and –skip-plugins can leave plugins out.
- Run the commandThe command calls WordPress functions and reads or writes the database directly.
- Print and exitOutput goes to the terminal and a status code tells scripts whether it worked.
Installing WP-CLI and checking that it works
Before installing anything, check whether WP-CLI is already there. Many hosting plans that include SSH ship it preinstalled, and server panels that manage WordPress sites often do as well. Connect to the server (the next section shows how) and run this.
$ wp --info
If you get a block of text, you are done. If you get “command not found”, install it. You need a shell, a PHP command-line program that is recent enough (the official handbook states the current minimum, so confirm it there instead of trusting an old tutorial) and, for the wp db commands, a MySQL or MariaDB client on the same machine.
The recommended method on Linux and macOS is the phar. Download wp-cli.phar from the install page of the official WP-CLI handbook, then test it before making it permanent.
$ php wp-cli.phar --info
$ chmod +x wp-cli.phar
$ sudo mv wp-cli.phar /usr/local/bin/wp
$ wp --info
If you do not have sudo, as on most shared hosting, keep the file in your home directory instead, and add the export line to your shell profile (for example .bashrc) so it survives the next login.
$ mkdir -p ~/bin
$ mv wp-cli.phar ~/bin/wp
$ export PATH="$HOME/bin:$PATH"
Other routes exist. On macOS, Homebrew provides brew install wp-cli. Composer users can run composer global require wp-cli/wp-cli-bundle. On Windows the handbook describes a Composer install or a phar with a small wp.bat launcher, and many people simply use the Windows Subsystem for Linux, which gives them the same environment their servers have.
$ wp cli version
$ wp cli check-update
$ wp cli update
Now read the output of wp --info once, carefully, because it answers the questions that cause most beginner confusion. It shows the PHP binary being used, its version, which php.ini file was loaded, the MySQL client binary, the WP-CLI version and where WP-CLI looks for its configuration files. The detail that surprises people is that the PHP it reports is the command-line PHP, which is not necessarily the PHP that serves your site. On a server with several PHP versions installed the two can differ, and so can the extensions and the limits. The comparison below lists the differences that matter in practice.
The same site, two different runtimes
| Browser request | WP-CLI command | |
|---|---|---|
| PHP and settings | Web server PHP with its own php.ini | Command-line PHP, often with a separate php.ini |
| Who runs it | The web or pool user | Whoever is logged in to the shell |
| Time limit | Execution limit and web server timeouts | No execution limit by default; memory limit still applies |
| Request context | Host name, URL, cookies, a logged-in user | None, so use –url and –user when needed |
| Scheduled tasks | WP-Cron is triggered by visits | Nothing triggers it; run due events yourself |
| Output | A web page | Text, tables, JSON and an exit code |
Getting a shell: SSH, the right folder and the global flags
Most WP-CLI work happens on the server that hosts the site, over SSH. Your hosting panel tells you whether SSH is available and gives you a host name, a port, a username and either a password or a place to upload a public key. Some panels keep SSH off until you enable it per site or per user, and some plans do not offer it at all, so read your plan’s documentation instead of assuming. Panels that run WordPress on servers you rent often create a separate system user for each site, which matters in the next section.
Key-based login is better than a password: nothing secret crosses the network and scripts can connect without prompting. Create a key pair on your own computer, give the panel the public half and keep the private half private.
$ ssh-keygen -t ed25519
$ ssh deploy@server.example.com
$ ssh -p 2222 deploy@server.example.com
The first line makes the key pair. The second connects on the default port, 22. The third uses a different port, which some hosts require. Replace the user and host name with your own.
Once connected, find the WordPress folder: the one that contains wp-config.php, wp-content and wp-includes. The folder name varies by host. It might be public_html, www, htdocs or a path named after the domain, so look instead of guessing.
$ ls
$ cd public_html
$ ls wp-config.php
$ wp core version
WP-CLI searches the current folder and its parents for WordPress. If it prints a version number, you are in the right place. If you would rather not change directory, name the folder explicitly with --path, which also makes a command safe to paste into a script.
$ wp --path=/var/www/example.com/public core version
Learn the global flags now, because they work with every command. --path names the WordPress folder. --url names which site to act on, and is required on multisite. --user followed by a user ID or login runs the command as that WordPress user, which some plugin commands need because they check capabilities. --skip-plugins and --skip-themes load WordPress without them, and accept a list of names if you only want to skip particular ones. --quiet hides success messages and --debug prints what WP-CLI is doing, which you will want the first time something fails. The built-in manual is always one command away: wp help lists everything available, and wp help plugin update describes one command for the exact version you have installed.

Run it as the right user, with the right PHP and enough memory
The most common beginner mistake is running WP-CLI as root. It works, which is the trap. WP-CLI notices and refuses unless you add --allow-root, printing a warning that you probably meant to run it as the user your WordPress installation belongs to. Take that warning seriously. Files created by root, such as cache folders, generated thumbnails, plugin files unpacked during an update or an exported SQL file, end up owned by root. Later the web server user cannot write to them, and the symptoms look unrelated: an update that fails with a message about creating a directory, uploads that stop working, a cache plugin that cannot write. The flag exists for containers where root is the only user. On an ordinary server, do not use it.
So find out who owns the site. Check from the shell.
$ whoami
$ ls -l wp-config.php
$ ls -ld wp-content
The owner column shows the system user. On panels that give every site its own user, log in over SSH as that user and the problem disappears. On a server where one web user owns everything, run commands as that user instead. In the example, www-data is only a name; yours might be nginx, apache or a per-site account.
$ sudo -u www-data wp plugin list --path=/var/www/example.com/public
If you already ran something as root and created root-owned files, fix the ownership of exactly those paths with chown, or with your panel’s permissions tool. Do not change ownership of a whole server to cure one folder.
The second check is the PHP version. Compare what wp --info reports with the PHP version your site actually runs, which you can see in the hosting panel or in the Site Health screen. When a server has several PHP versions, the plain php command may be an older default. A command that loads a plugin needing newer PHP then fails on the command line with errors the site never shows. You can run the phar with the binary you want. Binary names differ by distribution, so ask your host.
$ php8.3 /usr/local/bin/wp core version
The third check is memory and extensions. The command line has no execution time limit by default, but the memory limit still applies and the command-line php.ini may set it lower than the web one. Heavy jobs such as a large search and replace, an import or regenerating thousands of thumbnails can hit “Allowed memory size exhausted”. Raise the limit for one command without editing any file.
$ php -d memory_limit=512M $(which wp) media regenerate --yes
$ php -m
The second line lists the PHP modules the command line has loaded. If the web PHP has the image library you rely on but the command-line PHP does not, thumbnail jobs fail or behave differently, so compare the lists before blaming WP-CLI.

Core commands: version, update and verify-checksums
Four commands answer three questions: what am I running, is it current, and are the files what WordPress.org shipped? Command 1 is wp --info, which you already met. Command 2 is wp core version, which prints the installed WordPress version and nothing else, so it is handy in scripts. Command 3 is wp core update. Command 4 is wp core verify-checksums.
$ wp core version
$ wp core check-update
$ wp db export before-core-update.sql
$ wp core update
$ wp core update-db
The check lists available releases, the export is your safety net and the update installs the new version. After a version jump WordPress may need to upgrade the database schema, which the dashboard would normally prompt for; wp core update-db performs that step from the terminal. Add --minor to wp core update when you only want maintenance and security releases within the current branch, which suits sites where a major jump needs testing first. You can pin a version with --version, and installing an older one needs --force, but treat that as a last resort: database upgrades do not reverse, so restoring a backup is the honest way back.
Command 4 deserves more attention than it gets. wp core verify-checksums downloads the official checksums for your WordPress version and locale and compares every core file on disk against them. It does not load WordPress, so it works on a site that will not boot. Output is one warning per file that differs, then a final error line, or a success line when everything matches.
$ wp core verify-checksums
$ wp plugin verify-checksums --all
Read the result as a lead, not a verdict. A modified wp-includes or wp-admin file is a strong sign of tampering or of someone editing core directly, which is a bad habit. A mismatch can also come from a locale or version mismatch, so if the report looks wrong, state them explicitly with --version and --locale. The check covers core only. The second command compares plugins hosted on WordPress.org against their published checksums; premium and custom plugins are not covered.
If core files do differ and you want clean ones, re-download the same version over the top. Passing the installed version matters: without it, the command fetches the latest release, which turns a repair into an unplanned upgrade. The --skip-content flag stops it re-adding the bundled themes and plugins, and the release package contains only a sample config file, so your wp-config.php is left alone. Take an export first, and verify again afterwards.
$ wp core download --version=$(wp core version) --force --skip-contentPlugins and themes: list, install, update, deactivate, activate
Commands 5 to 9 cover day-to-day plugin and theme work: wp plugin list (5), wp plugin install with --activate (6), wp plugin update (7), wp plugin deactivate (8) and wp theme activate (9). Start with reading, because the list is the best overview you can get in one screen.
$ wp plugin list
$ wp plugin list --update=available
$ wp plugin list --status=active --fields=name,status,update,version --format=csv
$ wp plugin install query-monitor --activate
Any column can act as a filter, so --update=available shows only plugins with a pending update. The --fields flag picks columns and --format chooses table, csv, json, yaml or count. The install line pulls a plugin from the WordPress.org directory by its slug and switches it on in one step; you can also pass a path to a zip file for a premium plugin you downloaded.
Updating is where a preview earns its keep. --dry-run prints what would be updated without changing anything. --exclude removes named plugins from the batch, which is how you hold back a complicated one such as a shop plugin until you can test it alone. The --minor and --patch flags limit updates to smaller version jumps, a sensible choice for cautious maintenance, although plugin authors do not all follow tidy version numbering, so a small jump is a hint, not a guarantee.
$ wp plugin update --all --dry-run
$ wp plugin update --all --exclude=woocommerce
$ wp plugin install plugin-slug --version=1.2.3 --force
The last line shows the rollback route for a plugin hosted on WordPress.org: install a named older version over the current one. Replace plugin-slug and the version number with your own, taken from your records. Premium plugins add a wrinkle. Their updates often depend on the vendor’s own updater and a valid licence, and that updater may behave differently outside the dashboard, so test one before you trust a bulk run.
For rescue work, remember the difference between two ways of switching plugins off. --skip-plugins loads WordPress without them for a single command and changes nothing stored. wp plugin deactivate changes the stored active list and runs each plugin’s deactivation code, which some plugins use to clear settings or caches. Save the list first, so you can restore it.
$ wp plugin list --status=active --field=name > active-plugins.txt
$ wp plugin deactivate --all
$ wp plugin activate query-monitor
Themes work the same way. wp theme list shows which is active, which is the parent of a child theme and which have updates. wp theme activate switches the live theme at once, and settings stored per theme, such as menu locations, may not carry across, so rehearse on staging.
$ wp theme list
$ wp theme activate twentytwentyfive
$ wp theme update --allA safe plugin update routine
- Export the databasewp db export to a dated file kept off the web root.
- List what is pendingwp plugin list –update=available shows exactly what would change.
- Dry runwp plugin update –all –dry-run previews the batch without touching anything.
- Update a small batchName plugins, or use –exclude to hold back risky ones such as a shop plugin.
- Check the siteLoad the front end, the admin and one key flow such as checkout or a form.
- Clear cacheswp cache flush plus your page cache, then recheck in a private window.
- Roll back if neededReinstall the named older version, or restore the export if data changed.
Users, options and wp-config constants
Commands 10 to 14 handle accounts and settings: wp user list (10), wp user create (11), wp user reset-password (12), wp option (13) and wp config (14). Users first, because this is where WP-CLI rescues people. Auditing administrators is the first move on a site you have just inherited or suspect was compromised.
$ wp user list --fields=ID,user_login,user_email,roles
$ wp user list --role=administrator
$ wp user create editor2 editor2@example.com --role=editor --send-email
$ wp user reset-password admin --skip-email --show-password
$ wp user delete 12 --reassign=1
If you are locked out and outgoing mail is unreliable, --skip-email avoids a reset email that will never arrive and --show-password prints the new password in the terminal. Change it after logging in, and remember that anything you type is also saved in your shell history. That is why the examples avoid putting passwords in the command itself. The delete line matters for one reason: without --reassign, the user’s posts are deleted with the account, so always name a user who should inherit the content.
Options are WordPress settings stored in the options table, and they are the other half of everyday administration. Reading is harmless and often answers a question quickly, such as which address WordPress believes it lives at.
$ wp option get siteurl
$ wp option get home
$ wp option update blogname "Example Studio"
$ wp option update blog_public 0
$ wp option list --autoload=on --format=total_bytes
The blog_public line discourages search engines and is useful on a staging copy, but remember to turn it back on, because forgetting it on a live site is a classic traffic loss. The last command reports the combined size of options loaded on every request, a quick health indicator. Many options hold serialised arrays that plugins expect in a precise format. Do not hand-edit those. Use the plugin’s settings screen, or wp option patch for a nested value if you know what you are changing.
Constants in wp-config.php are managed with wp config. The detail that trips people is --raw. Without it, a value is written as a quoted string, and a string containing the word false is truthy in PHP, so debugging could stay on when you thought you had switched it off.
$ wp config get DB_NAME
$ wp config set WP_DEBUG true --raw
$ wp config set WP_DEBUG_LOG true --raw
$ wp config set WP_DEBUG false --raw
$ wp config shuffle-salts
Shuffling the salts invalidates every login cookie, so everyone is signed out. That is the right move after a suspected compromise and an annoyance otherwise. Be careful with wp config list, which prints database credentials, and never paste its output into a support ticket. If you copy wp-config.php before editing, keep the copy outside the public folder; a leftover backup inside the web root can be downloaded as plain text.
The database: export, import and query, and why backups come first
The database holds your posts, settings, users, orders and plugin data, so this is where backup discipline starts. Command 15, wp db export, writes the whole database to an SQL file. It runs the MySQL or MariaDB dump program behind the scenes, so that client must be installed and on the path. Put a date in the file name so you never overwrite yesterday’s copy, or send the output straight into a compressor with a dash in place of the file name.
$ wp db export before-changes-$(date +%F).sql
$ wp db export - | gzip > before-changes.sql.gz
Keep exports outside the public web folder, and copy important ones off the server. A backup that lives only on the machine it protects does not survive that machine. Restore one onto a staging copy occasionally, because an untested backup is a hope, not a plan. Remember also that an export holds the database only: uploads, themes and plugin files are separate, so pair it with a file backup or a host snapshot.
Command 16, wp db import, loads an SQL file. Export files normally drop and recreate each table, so an import replaces what is there. Importing an old export over a live shop quietly discards every order placed since it was taken, which is the costliest import mistake there is. Command 17, wp db query, runs SQL directly, and is excellent for looking. Confirm the table prefix first, because it is not always wp_.
$ wp db import before-changes.sql
$ wp db prefix
$ wp db query "SELECT post_status, COUNT(*) FROM wp_posts GROUP BY post_status"
Three companions are worth knowing. wp db size --tables lists tables by size and often points straight at a bloated log or session table. wp db check runs the server’s table check. wp db optimize rebuilds tables and can lock them while it works, so run it in a quiet hour. At the dangerous end sit wp db reset and wp db drop, which empty or delete the database; they ask for confirmation unless you add --yes, and there is almost never a reason to put that flag in a script you wrote by hand. Any UPDATE or DELETE you pass to wp db query runs at once with no undo, so give it the same respect as production SQL.
How much damage a command can do
How to read this: each row is one option, and its dot shows where it sits between Only reads and Destroys data. Placement is an editorial judgement, not a measurement.
- 1wp plugin listReads and prints; nothing changes.
- 2wp db exportReads the database and writes a file; the one command that protects you from the rest.
- 3wp cache flushThrows away cached copies that WordPress rebuilds, though the site may be slower briefly.
- 4wp plugin update –allChanges code and sometimes database tables; reversible only with a backup.
- 5wp search-replace without a dry runRewrites stored data across tables; a wrong pattern is hard to reverse.
- 6wp db resetEmpties the database; only a backup brings it back.
Search-replace: changing domains and paths without breaking serialized data
Command 18 is the one that makes WP-CLI famous and the one that most often hurts people. WordPress stores addresses everywhere: in posts, widgets, menus, builder layouts and plugin settings. After a migration or a domain change, old addresses linger. A plain SQL REPLACE looks like the answer but corrupts data, because many settings are stored as PHP serialized strings that record each value’s length. Change a domain from one length to another and the stored length is wrong, so WordPress discards the whole value. wp search-replace unserializes, replaces and serializes again, which is why it is the right tool.
$ wp search-replace 'old.example.com' 'new.example.com' --dry-run
$ wp search-replace 'old.example.com' 'new.example.com' --skip-columns=guid --report-changed-only
The first line changes nothing and prints how many replacements it would make in each table. Read that table. A surprising count, or a table you did not expect, means your pattern is too broad. The second line does the work. Skipping the guid column matters because a post’s GUID is meant to stay constant, since feed readers treat it as the identity of the item, and changing it can make old posts look new. The report flag keeps the output to tables that actually changed.
Choosing the search string is the real skill. A bare domain without the scheme catches both the http and https forms, and also the escaped form that appears inside JSON, where slashes are stored with backslashes. It will also rewrite email addresses and plain text mentions that contain the domain, so check the dry run for them. When you are changing the scheme itself, pass the full old and new addresses including the scheme. A very short or common string, such as a word that appears in your content, will match far more than you intend. When in doubt, write the proposed change to a file with --export and read it instead of modifying the database.
Other flags you will meet: --all-tables includes tables without your prefix, which helps for custom plugin tables but also reaches tables of other applications sharing the database. --network covers a multisite network. Remember what search-replace cannot touch: theme and plugin files, constants such as WP_HOME in wp-config.php, CDN settings held outside the database, and CSS files that page builders generate. After the run, flush caches, flush rewrite rules, regenerate builder CSS if you use one, and click through the front end, the admin, media and one form.
A search-replace run in the right order
- Export the databasewp db export so a wrong pattern can be undone.
- Dry runAdd –dry-run and read the per-table counts for surprises.
- Narrow the patternPrefer a bare domain, and exclude guid; watch for email addresses and short strings.
- Run for realSame command without –dry-run, with –skip-columns=guid.
- Flush caches and rewriteswp cache flush and wp rewrite flush, then regenerate builder CSS if needed.
- VerifyFront end, admin, media, forms and a few old posts; keep the export for a while.
Caches, transients, rewrite rules, cron and maintenance mode
Five commands deal with the housekeeping that follows almost every change. Command 19, wp cache flush, clears the WordPress object cache. Whether that does anything depends on the setup. Without a persistent object cache, cached values live for a single request, so a flush has nothing durable to clear. With a Redis or Memcached drop-in, it can clear the whole store, and if several sites share it without separate key prefixes, you may clear their caches as well. wp cache type reports which implementation is in use. A page cache or CDN is a separate layer that wp cache flush does not touch; many cache plugins register their own purge commands, which wp help lists while the plugin is active.
Command 20, wp transient delete, removes temporary cached values that plugins and themes store. --expired deletes only those past their lifetime, which is safe housekeeping. --all also deletes unexpired ones, so plugins must rebuild them, possibly by calling remote services again. Where a persistent object cache is active, transients live there instead of the database. wp transient list lets you look first.
$ wp cache type
$ wp cache flush
$ wp transient delete --expired
$ wp rewrite flush
Command 21, wp rewrite flush, regenerates the rules that map pretty URLs to content. Use it when a new post type, taxonomy or permalink structure gives 404 pages. A plain flush rebuilds the stored rules. Adding --hard also rewrites the .htaccess file, which applies to Apache-style servers but not to nginx.
Command 22 is wp cron event run. WP-Cron fires when visitors arrive, which makes it unreliable on quiet sites and heavy on busy ones. From the shell you can see and run what is waiting. The due-now option runs only the events that are due and, according to the documentation, respects the lock that prevents overlapping runs.
$ wp cron event list
$ wp cron event run --due-now
Command 23 is wp maintenance-mode with activate, deactivate, status and is-active. Use it around risky manual work, then switch it off again; a site left in maintenance mode is a silent outage. A page cache or CDN may keep serving normal pages regardless, so confirm in a private window rather than trusting the status line.
$ wp maintenance-mode activate
$ wp maintenance-mode status
$ wp maintenance-mode deactivateWhich housekeeping command fits the symptom?
Posts and media: bulk tasks with list, delete and regenerate
Commands 24 and 25 handle content in bulk. Command 24 is the wp post family, mainly list and delete. Its power comes from --format=ids, which prints bare IDs that another command can consume, and --format=count, which prints how many matched. The pattern to adopt is list, count, back up, delete. Never delete from a list you have not counted.
$ wp post list --post_type=page --fields=ID,post_title,post_status
$ wp post list --post_type=revision --format=count
$ wp post delete $(wp post list --post_type=revision --format=ids) --force
$ wp post create --post_type=page --post_title="Notes" --post_status=draft
The third line removes every stored revision, which shrinks a bloated database and also erases edit history for good. Decide that on purpose. To limit future revisions, wp config set WP_POST_REVISIONS 10 --raw writes a cap to wp-config.php. With tens of thousands of IDs the shell may refuse the command with an argument list error. Feed the IDs in batches instead.
$ wp post list --post_type=revision --format=ids | xargs -n 100 wp post delete --force
When no ready-made command fits, wp eval runs a snippet of PHP inside the loaded WordPress and wp eval-file runs a PHP file. They can do anything WordPress can do, so treat them like a deployment, not a calculator.
Command 25 is wp media regenerate. When you change themes, or a theme or plugin registers new image sizes, existing uploads still have the old thumbnails. Regeneration rebuilds them. The flags decide the cost: --only-missing creates just the sizes an image lacks, --image_size limits the job to one registered size, and --yes skips the confirmation that appears when you do not name specific attachments.
$ wp media regenerate --only-missing --yes
$ wp media regenerate --image_size=large --yes
Know the side effects. By default the old thumbnails are deleted, which breaks any post or external page that hard-coded their file names, and the documentation offers --skip-delete for that situation. The job is heavy on CPU and disk, so run it outside peak hours and snapshot the uploads folder first. It also uses the command-line PHP’s image library, which, as noted earlier, may differ from the web one, and image optimisation plugins may react to each regenerated file.
Aliases, config files and scripts for managing several sites
Once you manage more than one site, retyping paths and SSH details gets tedious and invites mistakes. WP-CLI reads configuration files so you state those details once. A wp-cli.yml in a project folder applies to commands run there, and a file in your home directory, normally ~/.wp-cli/config.yml, holds personal defaults. Flags typed on the command line beat both. Inside a project file you can set global flags as keys, for example the WordPress folder when core lives in a subfolder, and block commands you never want run by accident.
path: web/wp
disabled_commands:
- db drop
- db reset
Aliases name a remote site once and let you run any command against it over SSH. The ssh value follows the same format as the --ssh flag, with the folder appended to the host. A group is simply a list of aliases.
@prod:
ssh: deploy@example.com/var/www/example.com/public
@staging:
ssh: deploy@staging.example.com/var/www/staging.example.com/public
@both:
- @prod
- @staging
$ wp @prod core version
$ wp @staging plugin list --update=available
$ wp @both plugin list --update=available
This needs WP-CLI installed on the remote server and key-based SSH so nothing prompts for a password. Build one habit: before any change, ask the target where it thinks it is, for example wp @prod option get home, so a typo in an alias name cannot send a destructive command to the wrong site.
Scripts add repeatability. Commands exit with zero on success, so a script can branch on wp core is-installed, wp plugin is-installed or wp maintenance-mode is-active. Under cron the search path is minimal, so use the full path to wp and pass --path. In the sample, pipefail makes a failed export stop the script instead of leaving an empty archive you mistake for a backup.
#!/bin/bash
set -euo pipefail
SITE=/var/www/example.com/public
DEST=/home/deploy/backups
mkdir -p "$DEST"
/usr/local/bin/wp --path="$SITE" db export - | gzip > "$DEST/db-$(date +%F-%H%M).sql.gz"
find "$DEST" -name 'db-*.sql.gz' -mtime +14 -delete
The same approach replaces WP-Cron with a real schedule. Set wp config set DISABLE_WP_CRON true --raw once, then add a crontab line for the site user. For long jobs run over SSH, such as a big search and replace, start them inside tmux or screen so a dropped connection does not kill them halfway.
*/10 * * * * /usr/local/bin/wp --path=/var/www/example.com/public cron event run --due-now --quietWhere WP-CLI settings come from
Troubleshooting: the errors beginners meet and what to do next
Most WP-CLI failures fall into a few families, and the first line of the error usually tells you which. Before guessing, rerun the command with --debug for detail, check wp --info for the PHP and user in play, and try the command with plugins and themes skipped.
$ wp --skip-plugins --skip-themes core version
$ wp --debug plugin list
“Command not found” means WP-CLI is not installed or not on your path. Call it by its full path, or install it as shown earlier. The same cause hits cron jobs, which run with a minimal path.
“This does not seem to be a WordPress installation” means you are in the wrong folder. Change into the folder holding wp-config.php, or pass --path.
“Error establishing a database connection” means WordPress started but could not reach the database with the details in wp-config.php. Check that you are on the right server, because a container or a separate database host can be reachable from the web process and not from your shell. Check the credentials and whether the database service is running.
Database commands that fail with a message about a missing dump or client program point at a different cause: wp db commands call the MySQL or MariaDB client programs, so those must be installed and findable. Other commands use PHP’s own connection, which is why some commands work while those fail.
A fatal error, a critical error message or a stack trace naming a plugin or theme means that code broke while WordPress loaded. Skip everything first, then narrow down by naming skips, for example --skip-plugins=plugin-slug. “Is not a registered wp command” usually means the plugin providing that command is inactive or was skipped, or the command has a typo.
“Allowed memory size exhausted” needs more memory for that run, using the php flag shown earlier. Warnings about running as root and file permission errors both point back to the user you are running as. On multisite, a command that acts on the wrong site or errors on a host name needs --url. Finally, PHP notices printed before JSON can break scripts that parse output; fix the source or keep warnings out of the data.
If you must ask for help, include the exact command, the full error text, the output of wp --info and the --debug output with passwords, salts and database credentials removed.
A command failed: read the first line
Checklist
- Run wp –info and note the PHP binary, PHP version and php.ini; confirm the version matches your site.
- Log in as the site’s own system user, not root, before running anything that writes files.
- Run wp core version from the WordPress folder, or with –path, to prove you are in the right place.
- Export the database with a dated file name before any command that changes data.
- Store exports outside the public web folder and copy important ones off the server.
- Restore a backup onto a staging copy at least once to prove it works.
- Use –dry-run first for plugin updates and search-replace, and read the counts it prints.
- Count with –format=count before deleting posts, revisions or users.
- Name a user with –reassign when deleting accounts, so their posts are kept.
- Hold risky plugins back with –exclude and update in small batches.
- Save the active plugin list before running wp plugin deactivate –all.
- Pass –raw when setting true or false constants with wp config set.
- Skip the guid column in search-replace and check the dry run for email addresses and short matches.
- After updates or search-replace, flush caches and rewrite rules, then test the front end and admin in a private window.
- Use full paths, –path and set -euo pipefail in cron jobs and scripts, and confirm an alias target before changing it.
Read this next
About this guide. This is general guidance written by WPresident Editorial from documentation and widely used practice. WPresident has not benchmarked the products or methods described. Interfaces and plan limits change, so check the vendor’s current documentation before you act. Not legal, tax or financial advice. See our editorial policy.
Frequently asked questions
What is WP-CLI and do I need it?
WP-CLI is the official command-line interface for WordPress. You do not need it to run a site, but it saves real time on updates, database work, migrations and rescues, and it can do things a browser cannot, such as importing a very large database. If you manage more than one site, or have ever been locked out of the dashboard, it is worth learning.
Can I use WP-CLI on shared hosting?
Often, but not always. You need SSH access, a command-line PHP and, for database commands, a MySQL or MariaDB client. Some plans disable SSH or restrict it, and some hosts preinstall WP-CLI while others do not. Check your plan documentation or ask support, and if SSH is unavailable, ask whether your host can enable it. If you have no shell, your host's panel may offer some of the same tasks through its own tools.
Do I need to be root to run WP-CLI?
No, and you should not be. Use your normal site account instead. Run it as the system user that owns the site files. Running as root can leave root-owned files behind that the web server cannot write, which later shows up as failed updates or uploads. WP-CLI refuses to run as root unless you pass --allow-root, a flag meant for containers rather than ordinary servers.
Does WP-CLI work on Windows?
The official handbook describes installing it on Windows through Composer or a phar with a small launcher file. Many people prefer the Windows Subsystem for Linux, because it gives the same shell environment their servers use and avoids path differences. Whichever you pick, follow the current handbook for details, and practise on a local copy before touching a live site. Either route lets you follow every example in this guide.
How do I update WP-CLI itself?
For the standard phar install, run wp cli check-update to see whether a release is available and wp cli update to install it. If the file is owned by root you may need sudo. If you installed through a package manager such as Homebrew or through Composer, update it with that tool instead, so its records stay accurate. Check the result afterwards with wp cli version.
Is wp db export a complete backup?
No. It saves the database only: posts, settings, users and plugin data. Your uploads, themes, plugin files and wp-config.php are separate. A complete backup needs the files too, from a file archive, a host snapshot or a backup plugin. Store both off the server and test a restore on a staging copy before you rely on them. Many hosts also keep their own snapshots, which are worth using as well.
Is it safe to run wp plugin update --all on a live site?
It is safe only as safe as your preparation. Export the database, preview with --dry-run, hold back complicated plugins with --exclude and check the site afterwards. For shops, membership sites and anything with payments, rehearse the update on a staging copy first, because a successful command only means files were replaced, not that every feature still works. Updating a few plugins at a time also makes any breakage easier to trace.
Why does a command behave differently from the dashboard?
The command line is a different runtime, and that is normal rather than a bug. It can use another PHP version, another php.ini, different extensions and a different user, and it has no browser session, host name or visitors triggering cron. Run wp --info to see what it is using, compare with the site's PHP version, and pass --url or --user when a plugin expects that context.
Can I undo a search-replace?
Not reliably. Running the reverse replacement may not restore the original, because the new text may already exist elsewhere or the earlier change may have affected more than you intended. The dependable undo is restoring the database export you took first. That is why the routine is export, dry run, run for real and verify. Keep the export until the site has run normally for a while.
How does WP-CLI work with multisite?
Because a command line has no host name, tell WP-CLI which site you mean with --url, or run commands against the whole network where a command supports --network. Some commands act on one site by default and others on the network, so read wp help for the command, and test on a staging network before you run network-wide changes. Always confirm the target first.



