WordPress can also use the command line: wp-cli - Introduction and Practice
This article was last updated 149 days ago. The information in it may have developed or changed. If it is invalid, please leave a message in the comment section.

1 Introduction

In previous articles (see:Home Data Center Series WordPress Websites Use Simply Static Plugin to Make Sites Static), I detailed how to use the Simply Static plugin on WordPress to export dynamic websites into pure static pages with one click. This solution is very suitable for building a backup site with full-site caching, or directly deploying to platforms such as Cloudflare Pages to achieve extreme access speed and security.

In fact, if you only update the website occasionally, there is nothing wrong with manually clicking the "Generate Static Files" button on the dashboard. In fact, for my current update frequency, this method is sufficient. However, the problem lies in the word "manual":

  • Once the website is updated frequently, for someone like me who changes something small almost every now and then, it is easy to forget to click on it.
  • Not to mention that if you want to export on a weekly basis and then automatically synchronize it to the GitHub repository to trigger the redeployment of Cloudflare Pages, it is completely impossible to do so.

Although I still choose to export manually once a week, I have been looking for a way toAutomation possibilitiesIf there is a need to enable a fully automated process in the future, the WordPress command line tool wp-cli, is undoubtedly the most suitable solution. With wp-cli, I can call Simply Static's export action directly through the command line without opening the browser, and even combine Git, scheduled tasks, Docker and other tools to build an automated pipeline from dynamic sites to static sites.

Even if you don’t plan to automate for the time being, wp-cli itself is worth knowing. It is like a “command line panel” for WordPress, which can help us install plugins, update articles, manage users in a faster way... It is very friendly to those who like to use the command line.

Therefore, before entering the actual operation, let’s talk about wp-cli in a separate chapter, because this tool is actually worth mastering.

2 Introduction to wp-cli tool

2.1 What is wp-cli?

In simple terms, wp-cli is the command line interface (CLI) of WordPress. It allows you to manage and operate WordPress using the command line, and can almost replace the backend dashboard to complete most tasks. From an official perspective, the original intention of wp-cli is to improve the maintainability and automation capabilities of WordPress, allowing you to perform various batch operations without opening a browser, which is particularly suitable for the following scenarios:

  • CI/CD Workflow: You can work with GitHub Actions / GitLab CI to do something during the deployment phase.
  • Large-scale station group management: One line of script can perform operations on hundreds of sites.
  • Automated operation and maintenance scripts: For example, export data regularly, clear cache automatically, and check for updates daily.
  • Including what I'm going to use this time—— Call Simply Static plugin for static export

It can be understood as the "script entry" of WordPress. If your blog is a factory, you usually need to click the backend button to queue up for processing. Now with wp-cli, you can directly type commands in the terminal and the machine will start running immediately. It can be said that for those who pursue extreme controllability and automation, wp-cli is an indispensable "superpower" tool for WordPress.

2.2 Two deployment methods of wp-cli

2.2.1 First, deploy directly in the WordPress host (or Docker container)

This is actually the most common way.

  • If your WordPress is running directly on a Linux host (such as Debian), you only need to install wp-cli on the host through curl or apt.
  • If your WordPress is running in a Docker container, you can also install wp-cli into that container (usually with RUN curl … in the Dockerfile).

In this way, wp-cli can operate WordPress files, read and write databases directly on the same machine (or the same container) without any configuration, in the most natural way.

The downside is that if your container only has minimal PHP/FPM built in, or you want to keep your application container as "clean" as possible, you may not want to install wp-cli.

2.2.2 Second, deploy separately using the official docker image of wp-cli

A more elegant and decoupled approach is to use the wordpress:cli Docker image provided by WordPress. This image comes with wp-cli and PHP + necessary extensions, but does not include web services, and is only used to execute CLI commands.

Its principle is actually very simple:

  • Start this container via docker run or docker-compose.
  • Use -v to mount the WordPress directory on the host or in another container into the CLI container, giving it access to wp-config.php and wp-content.
  • Then connect to the same database through environment variables or existing configuration in wp-config.php.

This satisfies two key points at the same time:

1. Ability to manipulate WordPress files(such as generating static files, modifying themes, and installing plug-ins)

2. Ability to operate WordPress database(Because wp-cli will read wp-config.php or use the –dbhost parameter to connect to the database)

So as long as the folder is mounted and the database address is reachable (for example, the mysql/mariadb container is visible on the network), wp-cli can work just like it does in place.

2.2.3 Summary

Way Applicable scenarios and features
Method 1: Deploy directly on the host machine (or Docker container) More suitable for thatDeploy WordPress from host source code(For example, in /var/www/html). At this time, the files and database are in the same environment, and wp-cli can be installed on the local machine or in the container and can be used directly, with almost zero configuration.
Method 2: Run wordpress:cli separately using docker run More suitableDeploy WordPress with Docker In this case, WordPress and MySQL are separate containers. This allows you to use the official cli image to run the task container separately, operate WordPress files by mounting volumes, and access the database through the container network. This is lightweight and decoupled, and also convenient for subsequent migration to other machines or writing to CI/CD for automatic execution.

For what I want to do, "scheduled execution of Simply Static to generate a static site", the second method is suitable: using a Docker image to run wp-cli alone, which can both mount WordPress files and access the database through the network, which is a very elegant approach.


Although wp-cli provides very powerful command line operation capabilities and supports common functions such as plugin management, theme operation, database export and import, and article publishing, it is not a "universal remote control" for WordPress:
•Some plugin or theme settings rely on front-end page interactions, or are stored in complex option structures, and wp-cli cannot always handle these configurations accurately.
•Some functions that require user authorization (OAuth) and graphical interface configuration cannot be covered by wp-cli.
•In addition, wp-cli bypasses some of the logic verification processes at the UI layer when operating the database. Although this is efficient, it may cause data consistency issues or omit necessary side effects.

For example:
•The connection process of the Jetpack plugin involves the OAuth authorization jump of WordPress.com. wp-cli cannot complete the authentication binding through the command line and can only be manually authorized in the background dashboard.
•The page structure of visual builders such as Elementor is often stored as complex JSON data fragments. Even if you use wp-cli to modify it, it is difficult to ensure the accuracy of the front-end layout.
•Some security plugins (such as Wordfence and iThemes Security) will dynamically generate configuration files or firewall rules in the background after being enabled. These mechanisms are also not controlled by wp-cli.

Therefore, it is more suitable as a tool for scenarios such as scripting, batch operations, and automated deployment, rather than completely replacing the dashboard operation method.


3 Deployment of wp-cli tool

3.1 Method 1: Deploy directly on the host machine (or inside a Docker container)

3.1.1 Install wp-cli on the host machine

If your WordPress is deployed on a server in the most traditional way, such as putting the source code directly in /var/www/html, using nginx or apache to provide services, and the database is on the same machine or in the same LAN, then the easiest way is to install wp-cli directly on this host machine. The most common method is to use the official installation script:

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar php wp-cli.phar --info # Test whether it can be executed normally chmod +x wp-cli.phar sudo mv wp-cli.phar /usr/local/bin/wp

This way you can use it globally through the wp command, for example:

wp --info wp core version

If you deployed WordPress from source code, you only need to specify the path when executing, and your plugin list will be listed:

wp --path=/var/www/html plugin list

3.1.2 Install wp-cli inside the WordPress container

Similarly, if you use a common container method to deploy WordPress (for example, using docker run or docker-compose to start WordPress + MySQL), you can also install wp-cli in the WordPress container through apt install or curl. Because the container itself already has the PHP runtime environment and the WordPress file directory, as long as you can execute php commands, you can run wp-cli. For example, enter the container first:

docker exec -it your_wordpress_container bash

Then execute:

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar php wp-cli.phar --info chmod +x wp-cli.phar mv wp-cli.phar /usr/local/bin/wp

In this way, the wp command can be executed directly inside the container.


It should be noted that many WordPress images are very slim, containing only PHP + Apache/Nginx + WordPress files. The most common tools such as curl and wget may not be installed. If they are not installed, to use them in the container, you often need to execute the following command first:

apt update && apt install curl wget less -y

What's more troublesome is that this method is only valid in the current container -
If you later execute docker-compose down and then up, or if a new image is pulled because of WordPress automatic updates, all previously installed tools will be lost (unless written into the Dockerfile).

Therefore, if you want to install wp-cli in the scenario of deploying WordPress with Docker, it is recommended to use the wordpress:cli image described in the next section to execute it separately. This is more lightweight and decoupled, and you don’t have to worry about the environment disappearing after the container is rebuilt.


3.2 Method 2: Deploy separately using the official docker image of wp-cli

3.2.1 Deployment using docker-compose

Compared with installing wp-cli inside the WordPress container, the more recommended way is to directly use the official wp-cli image to deploy a separate container. This is cleaner, more isolated, and easier to reuse, especially suitable for scenarios where multiple WordPress instances are already managed through docker-compose.

You can add a wp-cli container directly to the existing docker-compose.yml, for example:

wpcli: image: wordpress:cli container_name: wpcli volumes: - ./html:/var/www/html entrypoint: tail -f /dev/null

There are a few points to note about this configuration:
• The container uses tail -f /dev/null to keep suspending without exiting, so that we can docker exec to execute commands at any time;
• volumes corresponds to the WordPress data directory, it is recommended to keep it consistent with the WordPress container (you can change it to your own path);
• Network, database and other services are not bound separately because most of our operations are to run the wp command to process static files locally or cooperate with HTTP requests, which is sufficient if the database is not involved.

Once you have deployed this container, you can enter wp-cli like this:

docker exec -it wpcli bash

Then execute the command directly in the container, for example:

wp --path=/var/www/html plugin list

The benefits of doing this are:
• Avoids modifying the environment in the WordPress image;
• Avoid losing wp-cli due to container destruction or image upgrade;
• Easier to manage in a unified manner and also facilitates subsequent automated script packaging.

If you want to go a step further, you can also write a dedicated Dockerfile to predefine some parameters, such as configuring the default path, default URL, etc. But for most scenarios, using the official image directly is good enough.

3.2.2 docker-run command format deployment

In addition to the docker-compose method, you can also use the more direct docker run command to run the wp-cli official image. This method does not require modifying the existing docker-compose.yaml file, nor will it affect the running status of the existing WordPress container. Therefore, it is more secure in some environments that require higher stability.

For example, you can usedocker runExecute the wp-cli command directlywp plugin list:

docker run --rm \ --volumes-from your-wordpress-container \ --network container:your-wordpress-container \ -it wordpress:cli \ wp plugin list

This command does the following:
• –rm: automatically clear after the container exits;
• –volumes-from: reuse the persistent data volumes of the WordPress container;
• –network container:…: directly join the network namespace of the WordPress container to ensure that the wp-cli command can connect to the database used by WordPress;
• wordpress:cli: use the official wp-cli image;
• wp plugin list: Run the example command to list the plugins.

This method is suitable for temporary operations or script calls. It exits after execution and avoids making any changes to the docker-compose.yaml of wordpress. It is neat and lightweight and does not require changing the deployment structure.

If you need to run multiple wp-cli commands in a container and do not want the container to exit after each command, do not add the –rm parameter and start a persistent wp-cli container like this:

docker run --name wp-cli \ --volumes-from your-wordpress-container \ --network container:your-wordpress-container \ -it wordpress:cli /bin/bash

If you need to enter the container again to perform operations, you can choose one of the following two methods depending on the situation:

  • docker exec -it wp-cli /bin/bash: Enter the container's shell, suitable for executing multiple commands;
  • docker start -ai wp-cli: Re-enter the wp-cli container main process (if the main process is an interactive wp command).

Notice: If you stop the container with docker stop wp-cli, you can start it again with docker start -ai; if the container is still running, it is recommended to enter it directly with docker exec.


If you get a warning like Undefined array key "HTTP_HOST" when executing the wp command, it's usually because some plugins/themes in CLI mode are still trying to read HTTP header information, which doesn't exist in the context of wp-cli.
These warnings will not affect the actual results of the command and can be ignored. If you need to block them, you can consider adjusting the PHP error output level by mounting a custom php.ini:

image.png


4 Introduction to common wp-cli commands

The following is an introduction to common wp-cli commands and their functions, covering common operations such as plugin management, theme management, database, user, cache, etc.

Plugin management related:

Order illustrate Example
wp plugin list List all plugins and their status (activated/inactivated) wp plugin list
wp plugin install Install plugin (not activated by default) wp plugin install akismet
wp plugin install --activate Install and activate the plugin wp plugin install akismet --activate
wp plugin activate Activate installed plugins wp plugin activate akismet
wp plugin deactivate Deactivate plugin wp plugin deactivate akismet
wp plugin delete Removing a plugin wp plugin delete akismet

Plugin and wp-cli extension support instructions

wp plugin list can only show the installation and activation status of the plugin, but cannot tell whether the plugin provides extended commands for wp-cli. Some well-known plugins (such as WooCommerce, Jetpack, etc.) provide exclusive commands for wp-cli to support more fine-grained management and operations.

To view all wp-cli commands supported by the current site, you can use:

wp help

Or query help for a plugin command space:

wp help

If the plugin documentation or official website does not clearly state it, you can try to use the above method to confirm whether it is supported. This method can help you discover more advanced usage of the command line and improve operation and maintenance efficiency.


Theme management related:

Order illustrate Example
wp theme list View all themes and currently active themes wp theme list
wp theme install Install the theme (not enabled by default) wp theme install twentytwentyfour
wp theme activate Enable the specified theme wp theme activate twentytwentyfour

User management related:

Order illustrate Example
wp user list List all users wp user list
wp user create Create a New User wp user create alice [email protected] --role=editor
wp user delete Delete User (Optional Transfer Content) wp user delete 3 --reassign=1

View site information:

Order illustrate Example
wp option get Get site configuration item value wp option get siteurl
wp option update Modify the value of a site configuration item wp option update blogdescription "new subtitle"

Cache operation related:

Order illustrate Example
wp cache flush Clear the object cache (such as using Redis, etc.) wp cache flush
wp transient delete --all Delete all transients wp transient delete --all

Database operation related:

Order illustrate Example
wp db export Export database to SQL file wp db export backup.sql
wp db import Import SQL file wp db import backup.sql
wp db reset Reset database (clear all data) wp db reset
wp search-replace Full site text replacement (including database) wp search-replace 'http://old.com' 'https://new.com'

wp core related operations:

Order illustrate Example
wp core update Update WordPress core wp core update
wp core version View the current WordPress version wp core version

This is just the tip of the iceberg of wp-cli, which has very powerful scripting capabilities. If you are maintaining multiple WordPress sites or planning to automate your deployment process, it is worthwhile to learn wp-cli in depth.

Note: Many commands support --allow-root and --path=/var/www/html Parameters such as , can be adjusted according to the operating environment.

5 Use wp-cli to implement timed export of simply static pro

5.1 Overview


This is a live record of my habit of jumping into whatever goal I think of, and then "researching and recording" as I go: I originally wanted to use wp-cli to schedule the export task of Simply Static, but just after writing a few commands with great enthusiasm, I found that the free version was not working at all.No support for wp-cli:

image.png

Then I looked at the simply static official website and found that this is only for pro subscriptions:
image.png

So this leaves me hanging in the air... But since the pit has been dug, I will still write down the research process, but I want to remind you:Only Simply Static Pro supports wp-cli commands, free version users should not waste their time. If you really want the free version to support wp-cli commands, you can only switch to a similar old plug-in.WP2Static", but the use of this software is a little more complicated than simply static. I chose simply static in the end just for the sake of simplicity.


The key command to implement the export of simply static pro is:

wp simply-static run --update=true

The purpose of this command is to call the core logic of the plugin and trigger a complete static site export task. It will generate the HTML file of the entire site according to the options you currently configured in the background (such as export path, content to be excluded, URL rewriting method, etc.).

But when using this command there is aProblems that are easy to fall into, is the uncertainty of "export time". When Simply Static performs an export, the time required for the export will be affected by the following factors:

  • The performance of the host on which WordPress is deployed (particularly disk I/O and PHP execution efficiency);
  • The volume of the site content (number of pages, size of media assets);
  • Whether some time-consuming features (such as URL replacement, including media files, etc.) are enabled in the export settings;
  • Is it the first export? (The first generation is usually much slower.)

In some cases, the export may take only 10 minsHowever, it may be extended to due to insufficient resources or too many pages.Tens of minutes or even hoursTherefore, you cannot simply use the "sequential execution" method in traditional shell scripts to run them all at once. For example, you cannot simply write:

wp simply-static run --update=true git add . git commit -m "auto update" git push

This writing method will cause subsequent commands to be executed before the export is completed, and the final submitted content may be incomplete or even empty. Therefore, if you want to automate the export task and chain subsequent operations, you must introduceAsynchronous processing or polling detection mechanism,That is to say, the script needs to determine whether the export is completed before it can perform subsequent Git commit or deployment operations.

5.2 Solution 1: Set a conservative timeout

Suitable:Understand the approximate export time of your site, or be willing to set a sufficiently redundant waiting time.

Suppose you observe that the full export takes 20 minutes in the first execution, you can set the script timeout to 30 minutes or even longer:

#!/bin/bash # Trigger the Simply Static export taskdocker run --rm \ --volumes-from your-wordpress-container \ --network container:your-wordpress-container \ -it wordpress:cli \ wp simply-static run --update=true # Wait long enough to ensure the export is completes sleep 1800 # Wait 30 minutes (1800 seconds) cd /your-export-path git add . git commit -m "auto update" git push

Note: After executing the export task for the first time, you can observe the actual time taken and adjust the sleep time accordingly.

5.3 Solution 2: Polling to check export status (suitable for scenarios where export is time-consuming and unstable and sensitive to efficiency)

#!/bin/bash # Trigger Simply Static export taskdocker run --rm \ --volumes-from your-wordpress-container \ --network container:your-wordpress-container \ -it wordpress:cli \ wp simply-static run --update=true # Poll for export completion, up to 1 hour (3600 seconds) for i in {1..60}; do status=(docker run --rm \ --volumes-from your-wordpress-container \ --network container:your-wordpress-container \ -it wordpress:cli \ wp simply-static status) echo "status" | grep -q "completed" && break echo "Waiting... $i minute" sleep 60 done # Push the exported content to the remote repository cd /your-export-path git add . git commit -m "auto update" git push

Note: This solution is more flexible and reliable, and can automatically identify whether the export is completed. It is suitable for production environments or sites with large changes in task duration.

5.4 Summary and Suggestions

There is no single correct approach to the automated export + push process. This article provides two solutions, each with its own applicable scenarios:

  • Scenario 1 It is more suitable for small blogs with small resource usage and fewer plug-ins. It has simple configuration and sufficient stability.
  • Scenario 2 It is more suitable for sites with complex structures and numerous plug-ins. It can effectively avoid uncertainties in the export process and is more secure.

It is recommended to make flexible choices based on the scale and actual situation of your site.

In addition, if you are using Simply Static Pro, in fact, you can directly push the exported content to the GitHub repository. However, we are currently mainly based on WP-CLI to achieve automation, and we are not very clear about the CLI support capabilities of this part of the Pro plug-in (mainly because we are too lazy to study it ~). If its support can be verified in the future, you can also try to directly call its push logic in the CLI to further simplify the entire process.

6. Afterword

If you want to automate WordPress-related functions, wp-cli can play a very important role. For example, I currently export the WordPress database directly in the MariaDB container using the docker exec command. With wp-cli, I can export the database directly with one line of command, for example:

wp db export /var/www/html/wordpress.sql

Compared with executing mysqldump through the database container, this usage of wp-cli is closer to the logic of WordPress itself, and the export path and permission issues are more controllable.

In addition to database exports, wp-cli can also be used to complete many common management operations, such as:

  • Enable or disable plugins:
wp plugin activate simply-static wp plugin deactivate akismet
  • Install and activate the theme:
wp theme install twentytwentyfour --activate
  • Update plugins/themes/Core:
wp plugin update --all wp theme update --all wp core update
  • Backstage user operations:
wp user list wp user create newadmin [email protected] --role=administrator

Not to mention the static site export task we mentioned above, which can also be scheduled through wp-cli.

Although the main line of this article is to achieve the automated deployment of Simply Static static sites, in fact, wp-cli can become the automation console of the entire WordPress system. Whether you want to back up the database, clean up the cache, enable plugins in batches every day, or plan to build a CI/CD automatic deployment process later, wp-cli is one of the most worthwhile tools to master. It is more like an "automation language" for WordPress, allowing you to get rid of tedious backend clicks and truly use scripts to manage the site.

If you are interested in more WordPress automation and operation and maintenance, it is well worth your time to explore the capabilities of wp-cli.

📌 Content Structure Hints:
This content belongs to "Blog Knowledge MapThis is part of the document; you can view the full content path here: Blog Knowledge Map .
Share this article
All blog content is original; please indicate the source when reprinting! The blog's RSS address is:https://blog.tangwudi.com/feed, welcome to subscribe; if necessary, you can joinTelegram GroupDiscuss the problem together.
No Comments

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠(ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ°Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
Emoticons
Emoji
Little Dinosaur
flower!
Previous
Next