When managing WordPress, manually performing tasks such as updating themes, managing plugins, or migrating sites through the browser-based admin interface (GUI) is time-consuming and prone to errors. Manual work results in significant inefficiencies, especially when managing multiple sites or repeating the same settings over and over again.
This is where WP-CLI, a powerful tool that allows you to manage WordPress from the command line, comes into play. With WP-CLI, tedious tasks like bulk updating plugins or performing safe bulk replacements within the database without corrupting serialized data can be completed in just a few seconds from the terminal.
In this article, aimed at web development engineers and WordPress administrators, we provide a detailed explanation focused on practical know-how that can be immediately applied in the field. We cover everything from the WP-CLI installation process and basic commands useful in daily operations to the specific use of “search-replace” for safely and reliably performing complex tasks such as site migrations.
- 1. What is WP-CLI? What It Can Do and the Benefits of Adoption
- 2. WP-CLI System Requirements and Installation
- 3. WP-CLI Basic Syntax and Usage
- 4. List of Essential WP-CLI Commands for Practical Use
- 5. Database Management and the Powerful Use of “search-replace”
- 6. [Practical Guide] Examples of Automation and Bulk Configuration Using WP-CLI (Integration with Shell Scripts)
- 7. Troubleshooting and Best Practices for Safe Operation
- 8. Summary – Speed Up WordPress Management with WP-CLI
1. What is WP-CLI? What It Can Do and the Benefits of Adoption
WP-CLI (WordPress Command Line Interface) is an open-source tool that allows you to manage and operate WordPress-based websites directly from the terminal (command line) without using a browser-based GUI.
It covers nearly all the functions available in the admin panel, and for some features, it allows you to perform more advanced operations more intuitively and safely than the GUI. By implementing WP-CLI, you gain the following three major benefits:
Dramatic Improvement in Work Efficiency
When using the WordPress admin panel, there is inevitably a wait time involved in navigating through screens—logging in, navigating to the desired page, waiting for the page to load, and clicking buttons. If there is network latency or slow server response times, this wait time can add up to significant losses.
With WP-CLI, simply typing “wp target-command” and press Enter, the process begins instantly, and you receive a completion notification. Simultaneous installation or updates of multiple plugins are also processed in parallel with a single command, resulting in significant time savings.
Programmatic Automation of Various Tasks
The greatest benefit of running tasks in the terminal is the ability to fully automate complex operational workflows by combining them with shell scripts (such as Bash) and “cron,” which schedules tasks on the server.
For example, if you create a script that fully automates the process of setting up a WordPress test environment—from creating the database to installing the core and installing and activating 10 specified recommended plugins—you’ll never need to perform manual setup again. This significantly reduces the initial burden on developers and ensures a consistent, uniform environment.
Safely and Reliably Performing Complex Tasks via GUI
As will be discussed later, when changing a site’s domain or implementing full-site SSL (HTTPS), you must replace old URLs in the database with new ones. If you use raw SQL toREPLACE, there is a risk that the “integrity of serialized data” will be compromised due to PHP specifications, potentially causing theme and plugin settings to be lost.
WP-CLI includes built-in functionality to identify this serialized state and perform accurate replacements, allowing you to handle site migration and maintenance far more reliably and quickly than using GUI plugins.
2. WP-CLI System Requirements and Installation
To use WP-CLI on a server or your local PC, you must meet several prerequisites.
System Requirements, Environment, and Use on Shared Servers
- OS Environment: Standard use is on UNIX-based environments (Linux, macOS, FreeBSD, etc.). For Windows, using WSL (Windows Subsystem for Linux) is strongly recommended.
- PHP: PHP 5.6 or later must be installed. However, considering the latest PHP features and security, it is currently recommended to use PHP 7.4–8.x as the runtime environment.
- WordPress: Version 3.7 or later. We generally recommend using the latest version.
- Server Environment Support: As long as the environment supports SSH connections and can run PHP, WP-CLI can be used not only on VPS (Virtual Private Servers) but also on general “shared servers.“ For example, even on shared servers like Lolipop, you can use it by logging in via SSH and
wp-cli.phar, you can use WP-CLI.
WP-CLI Installation Procedure
The installation itself is very straightforward. Simply download the executable archive file (PHAR) from the official site, grant it the necessary permissions, and move it to a directory included in your PATH. On shared servers, since you cannot navigate to system directories (/usr/local/bin/), so you’ll need to place it in your user directory ~/bin and add it to your PATH.
# 1. wp-cli.phar をダウンロード
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
# 2. 正しく動作するかテスト(情報が表示されればOK)
php wp-cli.phar --info
# 3. 実行権限を付与する
chmod x wp-cli.phar
# 4. コマンドラインから「wp」だけで呼び出せるように移動(管理者権限がある場合)
sudo mv wp-cli.phar /usr/local/bin/wp
After moving the file, enterwp --infoin the terminal. If the PHP version and WP-CLI installation path are displayed correctly, the installation is complete.
Using it in a Docker container (wordpress:cli)
Currently, it is common to use Docker/Docker Compose for local web development. If you do not want to install the PHP interpreter directly in the host OS’s local environment, or if you want to manage WordPress running inside a Docker container, use the wordpress:cli image provided by the official team.
You can either define a dedicated CLI container in `docker-compose.yml`, or create a temporary container at startup and execute commands immediately, as shown in the following command.
# docker-composeを利用して一時コンテナ上で WP-CLI(wp plugin list)を実行する例
docker-compose run --rm cli wp plugin list
3. WP-CLI Basic Syntax and Usage
WP-CLI features a hierarchical command structure, making it very intuitive to use. The basic structure is as follows.
Basic Structure: wp <コマンド> <サブコマンド> [オプション]
For example, to install and activate a plugin,wp plugin install autoptimize --activate.pluginis the main command indicating the target of the operation,installis the subcommand for the specific action, and--activaterepresents additional options.
Helpful help commands when you’re stuck
WP-CLI comes with a detailed built-in manual. If you find yourself wondering, “How do I use this command?” or “What options are available?”, try runninghelptry running the command.
# wpコマンド全体のヘルプを表示
wp help
# プラグイン関連のサブコマンド一覧と説明を表示
wp help plugin
# 個別アクションの詳しい使い方とオプションの仕様を表示
wp help plugin install
With this help feature, you can resolve most questions right in the terminal without having to open an interpreter or browser.
4. List of Essential WP-CLI Commands for Practical Use
Here’s a categorized guide to the essential commands you’ll want to memorize—the ones frequently used behind the scenes in daily operations and coding.
WordPress Core Management
Manages the version of the core WordPress software. This is invaluable for new installations and emergency data recovery.
- Checking the Current Version
wp core version - Downloading Core Files (Japanese Version)
wp core download --locale=ja - Updating the WordPress Core
wp core update
* Both minor and major updates can be performed with a single command. - Force reinstall core files (a recovery patch for cases where files are suspected of being tampered with or corrupted)
wp core download --force
Manage Themes and Plugins
For security reasons, you should always keep your themes and plugins up to date, but logging in and manually clicking through updates is a waste of time. With WP-CLI, you can perform these tasks all at once.
- List Installed Themes (or Plugins)
wp theme listwp plugin list
Their current status (active or inactive, pending updates) is displayed in a graphical table format. - Installing Plugins
wp plugin install
You can install plugins not only by their directory slugs but also by directly specifying the URL of a ZIP file distributed outside the official directory. - Batch update all plugins
wp plugin update --all
This is a very powerful and time-saving feature, but please make sure to always back up your site before running it to prepare for compatibility errors.
User Management and Recovery Measures
This is extremely effective when creating multiple accounts at once—such as when setting up a client testing environment—or for recovering from issues like “forgetting the admin password and being unable to access the admin panel.”
- Updating User Information (Password Reset)
wp user update <ユーザー名またはID> --user_pass="新パスワード" - Adding a New Administrator User
wp user create <ユーザー名> <メールアドレス> --role=administrator
*Note: Command history (.bash_historyor.zsh_history, etc.), so after performing these operations on a shared server, you must take precautions such as deleting the command-line history as appropriate.
Managing Posts, Tags, and Data
This command allows you to bulk generate dummy posts and check configuration information for terms (categories, tags, etc.) and custom post types.
- Generate Dummy Posts (for theme development or testing the pagination UI, etc.)
wp post generate --count=50
Automatically generates 50 pieces of test content with random content. Since it creates posts in an instant, this is an essential command for verifying pagination implementation and similar tasks. - Creating Tags for Blog Posts
wp term create post_tag "ニュース"
5. Database Management and the Powerful Use of “search-replace”
One of the true strengths of WP-CLI is its ability to interact directly with the database (DB). Here, we’ll explain essential practical tasks such as exporting data, executing direct queries, and performing powerful bulk replacements.
Database Export and Import (Note the Public Directory)
You can generate an SQL dump via command line before performing large-scale data replacements or for daily backup processes. Importing is just as simple.
# データベースをエクスポートする(※出力先に注意!)
wp db export ../backup-db.sql
# 万が一の場合は直ちにインポートしてリストア
wp db import ../backup-db.sql
[⚠️ Important Security Note]wp db export When executing this, if you save the output .sql file to the DocumentRoot (the public directory accessible via a browser), there is a critical risk that a third party could guess the URL, access it directly, and leak all personal information, including passwords. As
shown in the example output command ../backup-db.sql , be sure to export the file outside the public directory (DocumentRoot) or move it to a secure location immediately afterward, and manage it strictly.
Executing arbitrary SQL commands (wp db query)
It is also possible to execute arbitrary SQL queries (such as SELECT, UPDATE, and DELETE) directly from WP-CLI. This is extremely useful during operations because you can manipulate and verify data with a single command from the terminal without having to log in to the MySQL interface each time.
# 全ユーザーのIDとメールアドレスを一覧で取得する
wp db query "SELECT ID, user_email FROM wp_users;"
Basics and Key Benefits of Search-Replace (Bulk Replacement)
When changing a site’s domain or migrating/copying from a local development environment to a production server, it is essential to completely rewrite any URL strings contained within the site (e.g.,http://localhost:8000 → https://production-site.com) is essential.
As mentioned earlier, WordPress stores many configuration details (such as widget settings, plugin options, and theme settings) in the database in a format called “serialization.”Serialization is a mechanism for saving the structure of arrays and objects as strings, and a key feature is that it includes a definition of the “character count.” Therefore, if you simply force a replacement using raw SQL via tools like phpMyAdmin, and the character count of the domain URL
differs before and after the replacement, a discrepancy will arise between the defined character count and the actual string length. At that moment, the data will be corrupted, and all configuration information will be lost.
The WP-CLIsearch-replacedecodes and unpacks this serialized data, safely replaces the strings, and then reserializes it with the correct character count before saving it.
# 旧ドメインを新ドメインへ一括置換する基本形
wp search-replace 'https://old-domain.com' 'https://new-domain.com'
The Importance of a Pre-Replacement Backup
search-replace is a destructive operation that affects the entire database. Since there is a risk of accidentally replacing unintended strings, we strongly recommend that you **execute the aforementioned wp db export and obtain a safe backup of your database.**
Thorough Use of Dry-run and Exclusion Rules
In addition to taking a backup, make it a habit to always use the –dry-run (test run) option.
wp search-replace 'https://old-domain.com' 'https://new-domain.com' --dry-run
When this option is specified, the command enters preview mode, displaying only a report showing “which tables would be affected and how many records would be updated if the operation were actually executed,” without writing any data to the database. This allows you to clearly determine whether the replacement is on the scale you intended.
Also, please note that it is recommended not to carelessly modify the URLs in the “guid” column. GUIDs are used as unique identifiers for posts, and changing them in a production environment can lead to an incident where RSS feed readers and similar services mistakenly treat all previously distributed posts as entirely new articles and redistribute them en masse. To avoid this
, it is best practice to exclude this column as shown below.
wp search-replace 'https://old-domain.com' 'https://new-domain.com' --skip-columns=guid
6. [Practical Guide] Examples of Automation and Bulk Configuration Using WP-CLI (Integration with Shell Scripts)
WP-CLI truly shines when used to build custom workflows by chaining commands together. Here are two powerful use cases commonly employed in real-world scenarios.
Automated Setup Script for Launching New Sites
This example defines a single batch file that performs operations such as the WordPress installation process, generating database connection information (wp-config.php), installing essential plugins, and cleaning up unnecessary data.
#!/bin/bash
# wordpressディレクトリを作成し移動
mkdir wordpress
cd wordpress
# 日本語ロケールでコアファイルをダウンロード
wp core download --locale=ja
# wp-config.php の生成
wp core config --dbname='db_name' --dbuser='db_user' --dbpass='db_pass' --dbhost='localhost' --dbprefix='wp_'
# データベース自体の生成
wp db create
# WordPressの初期セットアップ(サイト名や管理者設定)
wp core install --title=test --admin_user=admin_user --admin_password=admin_password --admin_email=admin_email --url=https://wp.test
# 推奨プラグインの一括インストールおよび即時有効化
wp plugin install autoptimize duplicate-post ewww-image-optimizer password-protected svg-support --activate
echo "========================================"
echo " サイトの基本セットアップが成功・完了しました。 "
echo "========================================"
Save the above as setup.sh andbash setup.sh and run it, a complete development environment from scratch—including plugins—will be fully set up in literally a few seconds to a dozen or so seconds.
Advanced usage: Synchronizing a remote database with the production environment and configuring wp-cli.yml
You can execute and manage commands on the remote production environment via an SSH pipe from your local console. To do this, you must first place the configuration file wp-cli.yml in the project’s root directory and@prod and register “aliases (destinations)” such as
# wp-cli.yml の記述例
@prod:
ssh: [email protected]:2222/var/www/vhosts/production-site.com/httpdocs/
With this configuration in place, combining it with command-line piping (|) allows you to “stream and import raw SQL data exported from the remote server directly into your local environment.”
# 本番から最新DBを抜き出し、そのままローカルへ流し込み、ドメインを置換したのちキャッシュを消去する
wp @prod db export - --allow-root | wp db import - && wp search-replace 'https://before.com' 'https://after.com' && wp cache flush
With a one-liner command like this, the complex process of “copying production DB data to your local machine while simultaneously converting and applying it to your own testing URL” is completed in just a few dozen seconds.
7. Troubleshooting and Best Practices for Safe Operation
Since WP-CLI accesses deep parts of the system with very powerful privileges, executing it carelessly could lead to irreversible mistakes. Be sure to understand the precautions for safe operation.
Permissions and “–allow-root”
For security reasons, running WP-CLI as the OSrootenvironment or as the root user is prohibited (not recommended), and attempting to do so will halt the process with a red warning message. As a general rule, commands should be executed by a standard server user (the proper owner of the files).
However, if you must run it as root due to the initial state of a Docker container or unavoidable circumstances,--allow-root you must explicitly ignore the warning by adding the “–allow-root” flag. Please exercise extreme caution to ensure that file and directory permissions and ownership are not compromised.
Don’t forget to clear the cache
After performing operations such as directly modifying data using WP-CLI (e.g., search-replace or enabling/disabling plugins), or conversely, when encountering issues where “changes aren’t reflected even though the command
was executed” (the display doesn’t update), it is highly likely that WordPress’s object cache or transients (temporary data) are causing the problem. In such cases, please clear (flush) the cache using the following command:
wp cache flush
This will clear the database consistency and various cache settings, ensuring that the latest changes are immediately reflected in your browser.
8. Summary – Speed Up WordPress Management with WP-CLI
WP-CLI is no longer just a “bonus tool”; it has become an essential standard infrastructure technology in modern web development and operations workflows.
- Efficiency: Install, update plugins, and even back up the core with a single command
- A Step Toward Security:
search-replaceA golden rule for safely migrating or launching a site to a new domain while protecting serialized data.wp db exportto an external directory beforehand, and--dry-runand always perform testing and verification as an optional step. - Automation and Extensibility: Seamless integration with Bash shell scripts and cron jobs, plus
wp-cli.ymlcontrol integration with@prod.
You don’t need to memorize every command right from the start. Start by gradually incorporating safe operations—such as verifying targets (using reference commands like “wp plugin list” (commands for checking the target) and simple updates—start by gradually incorporating safe operations like these. You’ll soon notice a dramatic improvement in the speed and quality of your daily WordPress management and development tasks.

Comment