Working with WP CLI for WordPress Multisite

Over the years, WordPress developers have created and maintained WP-CLI, a robust command-line interface specifically designed for WordPress operations. As a time-saving tool, WP-CLI is particularly well-suited for managing WordPress Multisite networks, which allow multiple sites to run on a single WordPress installation.

To use WP-CLI effectively, it’s essential to understand key components of WordPress: the Admin interface, the file structure, and the database. Without this foundational knowledge, WP-CLI may not be as efficient or beneficial.

While WP-CLI supports standard commands like installing, updating, activating, deactivating, and deleting plugins or themes, its capabilities extend well beyond what’s available in the WordPress Admin dashboard, making it a highly versatile tool for advanced site management.

This article explains how to use WP-CLI to manage WordPress Multisite networks efficiently and provides practical examples to help you get started.

What is WP CLI and why use it?

WP-CLI is a powerful tool for managing WordPress sites via the command line. In a multisite environment, it can significantly simplify the management of a network, enabling you to perform bulk actions and streamline your workflow.

Its true strength lies in its flexibility and extensibility — you can effortlessly execute commands across the entire network or target specific sites while also enhancing its functionality with a variety of WP-CLI packages available on GitHub and other repositories.

Developers often create custom WP-CLI commands to simplify repetitive tasks. For example, you can use WP-CLI to scaffold boilerplate code for themes and plugins, saving time and effort during development.

If you’re hosting with Kinsta, WP-CLI is built-in and accessible via SSH, allowing you to manage WordPress sites effortlessly. For local development, WP-CLI is available in DevKinsta through the devkinsta_fpm container. Once inside the container, you can navigate to your site folder and run commands. While this requires a bit of setup, it provides a powerful way to manage your local WordPress sites efficiently for debugging, testing, or deploying.

Before you begin

The commands highlighted in this article are carefully chosen for their frequent use by WordPress Multisite developers and administrators.

WP-CLI is a broad and flexible tool, making it impossible to cover every available command. To keep things clear and practical, we’ve focused on simple, actionable examples to help you get started.

Since WP-CLI is based on Unix commands, you might not find a WP-CLI equivalent for commands that already exist in Unix.

Key notes about WP-CLI

WP-CLI’s command structure is flexible, allowing multiple ways to achieve the same outcome. For instance, both of the following examples are valid:

wp user create johndoe [email protected] --display_name="John Doe" --nickname="Johnny"

Or:

wp user create johndoe --display_name="John Doe" [email protected] --nickname="Johnny"

The order of flags, parameters, and values doesn’t matter once the command and subcommand are stated.

Best practices for running WP-CLI commands

Follow these best practices to avoid potential issues:

  • Always have a current backup available, especially as some of these commands will permanently alter your site(s).
  • Use a staging site wherever possible. If you’re using Kinsta, each WordPress install includes a free staging environment for safe testing. You can easily push changes between staging and live environments.
  • Use the --dry-run flag to test database changes before applying them.

Essential WP-CLI commands for WordPress Multisite management

WP-CLI commands in a Multisite network can target different levels of action:

  • Network-wide: Commands applied across all sites in the network. For example:
    wp plugin deactivate --network --all

    This command deactivates all plugins across every site in the network.

  • Primary site: Commands applied to the main site created during the Multisite setup. For example:
    wp plugin list

    The command above lists all plugins installed on the primary site only.

  • Secondary sites: Commands targeting individual sites within the network, specified by their URLs. For example:
    wp plugin update --url=mysite.example.com akismet

    This command updates the akismet plugin on the site mysite.example.com.

To make managing your Multisite network easier, we’ve grouped WP-CLI commands into these sections:

Basic commands

These fundamental commands help with troubleshooting and managing plugins and themes across your network.

Working with lists

WP-CLI makes it easy to retrieve lists of plugins and other components in your Multisite environment.

  1. Get a list of all plugins in the network:
    wp plugin list --network

    Output: Displays all network-installed plugins with details like name, status, updates available, and version.

  2. Filter plugins by status (e.g., active):
    wp plugin list --network --status=active

    Output: A table of active plugins across the network.

  3. Get a list of plugins from the primary site:
    wp plugin list

    Output: A list of plugins for the primary site.

  4. Get a list of active plugins for a single site:
    wp plugin list --url=<site-url> --status=active

    Input example:

    wp plugin list --url=blog.example.com --status=active

    Output: A table of active plugins for the site blog.example.com.

In addition to filtering plugins by status=active, you can also use the following filters:

  • inactive: Plugins that are installed but not active.
  • active-network: Plugins active across the network.
  • must-use: Must-use plugins that load automatically.

Deactivate plugins

Deactivating plugins is often necessary when troubleshooting issues or preparing for updates. WP-CLI allows you to deactivate plugins across the network or for specific sites.

  1. Deactivate all plugins across the network:
    wp plugin deactivate --network --all

    Result: All plugins in the network are deactivated.

  2. Deactivate specific plugins for a single site:
    wp plugin deactivate <plugin-slug-1> <plugin-slug-2> --url=<site-url>

    Input example:

    wp plugin deactivate akismet hello-dolly --url=blog.example.com

    Result: The plugins akismet and hello-dolly are deactivated for the site blog.example.com.

Activate plugins

Use these commands to activate plugins either network-wide or for individual sites in your Multisite setup.

  1. Activate all plugins across the network:
    wp plugin activate --network --all

    Result: All plugins in the network are activated.

  2. Activate specific plugins for a single site:
    wp plugin activate <plugin-slug-1> <plugin-slug-2> --url=<site-url>

    Input example:

    wp plugin activate akismet hello-dolly --url=blog.example.com

    Result: The plugins akismet and hello-dolly are activated for the site blog.example.com.

Install plugins

Installing plugins with WP-CLI is quick and efficient. Once installed, plugins can be activated for individual sites or across the network.

The following command can be used to install a plugin for the network:

wp plugin install <plugin-slug>

Input example:

wp plugin install akismet

Result: The plugin akismet is installed and ready for activation.

Update plugins

Keep your plugins up-to-date across your network or for specific sites using these commands.

  1. Update all plugins across the network:
    wp plugin update --network --all

    Result: All plugins in the network are updated.

  2. Update specific plugins across the network:
    wp plugin update <plugin-slug-1> <plugin-slug-2> --network

    Input example:

    wp plugin update akismet jetpack bbpress --network

    Result: The plugins akismet, jetpack, and bbpress are updated across the network.

  3. Update a plugin for a single site:
    wp plugin update --url=<site-url> <plugin-slug>

    Input example:

    wp plugin update --url=blog.example.com hello-dolly

    Result: The plugin hello-dolly is updated for the site blog.example.com.

Delete plugins

Removing plugins is straightforward with WP-CLI, whether you’re working on a single site or a Multisite network.

  1. Delete a plugin from the current WordPress context (network or site):
    wp plugin delete <plugin-slug>

    Input example:

    wp plugin delete bbpress

    Result: The plugin bbpress is deleted.

  2. Delete a plugin for a specific site in a Multisite:
    wp plugin delete <plugin-slug> --url=<site-url>

    Input example:

    wp plugin delete bbpress --url=blog.example.com

    Result: The plugin bbpress is deleted from the site blog.example.com.

Network management

Managing sites within a WordPress Multisite network is a crucial task. Below are common WP-CLI commands to help you efficiently create, manage, and delete sites, as well as handle caching operations.

Creating sites

Adding new sites to your network is straightforward with WP-CLI.

  • Basic command: Create a new site by specifying a unique slug.
    wp site create --slug=<site-name>

    Input example:

    wp site create --slug=blog

    Result: A new site blog.example.com or example.com/blog, depending on your network setup is created and is automatically active.

  • Advanced command: Alternatively, flags can be appended to the command. In the example below, a site is added with a specified site title and site administrator.
    wp site create --slug=<site-name> --title="<site-title>" --email=<admin-email>

    Input example:

    wp site create --slug=blog --title="Blog Site" [email protected]

    Result: A site titled “Blog Site” is created with [email protected] as the administrator.

  • List all sites: Retrieve a table displaying site IDs, URLs, creation dates, and last updated dates:
    wp site list

    You can also refine the site list to get only the URLs of all sites in the network:

    wp site list --field=url

    Output: A list of URLs for each site.

Emptying and deleting sites

  1. Empty the primary site:
    wp site empty

    Output: A confirmation prompt appears to delete all content for the primary site.

  2. Empty a single site (removes all posts, pages, links, and taxonomies):
    wp site empty --url=<site-url>

    Input example:

    wp site empty --url=blog.example.com

    Result: All content from blog.example.com is deleted, but the site remains intact.

  3. Empty all sites in the network:
    wp site list --field=url | xargs -n1 -I % wp site empty --url=% --yes

    Result: This command initiates a loop through all URLs and then proceeds to empty each site’s contents without the need to provide approval for each site.

  4. Delete a single site by ID:
    wp site delete <site-id>

    Input example:

    wp site delete 5

    Result: Site with ID 5 is deleted.

  5. Delete multiple sites with confirmation bypass:
    wp site delete 2 --yes
    wp site delete 3 --yes

    Result: Sites with IDs 2 and 3 are deleted. The --yes flag helps to skip prompts.

Clearing cache

Because many cache types are stored in different ways here, we use the Kinsta Must-Use plugin. It is installed automatically for each WordPress site in our system.

This clears all cache, including site cache, edge cache, CDN cache, and Redis cache.

  1. Clear all cache (site, edge, CDN, and Redis):
    wp kinsta cache purge --all
  2. Clear only site cache:
    wp kinsta cache purge --site
  3. Purge CDN cache:
    wp kinsta cache purge --cdn
  4. Clear object cache:
    wp cache purge

User management

WP-CLI simplifies managing users in a Multisite environment, allowing you to perform tasks quickly and efficiently. This section covers common user management operations:

List users

Listing users in a network or a specific site is straightforward with WP-CLI.

  1. List all users in the network:
    wp user list --network

    Output: A table showing User ID, Login, Display Name, Username, Registration Date, and Role for each user or user list query.

  2. List users for the primary site:
    wp user list

    Result: Displays a table of users for the primary site.

  3. List users for a specific site (secondary site):
    wp user list --blog_id=<id>
    wp user list --url=<url>

    Input example:

    wp user list --blog_id=6

    Result: Displays a table of all users for the site with Blog ID 6.

Create users

In a Multisite network, users are registered to the network by default. Their roles depend on whether they are the first user added to a site or subsequent users. Usernames must be at least four characters long.

  1. Add a new user to the primary site:
    wp user create <username> <email>

    Input example:

    wp user create johndoe [email protected]

    Output: A success message is displayed, including a generated password.

  2. Add a new user to a specific site with a specified role:
    wp user create <username> <email> --role=<role> --url=<url>

    Input example:

    wp user create janedoe [email protected] --role=editor --url=blog.example.com

    Output: The user janedoe is added to the site blog.example.com as an “Editor”.

  3. Add user account meta during creation:
    wp user create <username> <email> --display_name=<name> --nickname=<nickname>

    Input example:

    wp user create johndoe [email protected] --display_name="John Doe" --nickname="Johnny"

    Result: User johndoe is created with a display name John Doe and nickname Johnny.

Update user

Updating user information, such as roles or passwords, is quick with WP-CLI.

  1. Change (promote or downgrade) user roles:
    wp user update <username|email|user_id> --role=<role>

    Input example:

    wp user update johndoe janedoe adminuser --role=super-administrator

    Result: Users johndoe, janedoe, and adminuser are promoted to Super Administrators.

  2. Reset or change a user password:
    wp user update <username> --user_pass=<new_password>

    Input example:

    wp user update johndoe --user_pass=securePassword2024

    Result: The password for johndoe is updated.

  3. Daisy-chained commands: WP-CLI allows you to combine multiple actions in a single command, saving time when editing users. For example, you can simultaneously update a user’s password and role.
    wp user update <user> --user_pass=<new_password> --role=<status>

    Input example:

    wp user update johndoe --user_pass="newPassword2024" --role=editor

    Result: The password for user johndoe is updated to newPassword2024, and their role is changed to “Editor”.

Manage user meta

User meta allows you to add, retrieve, or delete metadata for user accounts.

  1. Get user meta:
    wp user meta get <username> <meta_key>

    Input example:

    wp user meta get johndoe nickname

    Output: Displays the value of the nickname meta key for user johndoe.

  2. Add user meta:
    wp user meta add <username> <meta_key> <meta_value>

    Input example:

    wp user meta add johndoe display_name "Mr. John Doe"

    Result: Mr. John Doe is set as the display name for user johndoe.

  3. Delete user meta:
    wp user meta delete <username> <meta_key>

    Input example:

    wp user meta delete johndoe display_name

    Result: This command deletes the display_name meta key for the user johndoe.

Delete users

Removing users from the network or specific sites is efficient with WP-CLI.

  1. Delete a user from the network:
    wp user delete <username|user_id> --network

    Input example:

    wp user delete johndoe --network

    Result: The user johndoe is removed from the network.

  2. Delete a user from a specific site:
    wp user delete <username|user_id> --url=<site-url>

    Input example:

    wp user delete johndoe --url=mysite.example.com

    Result: The user johndoe is removed from the site mysite.example.com.

Database management

WP-CLI provides a powerful alternative to tools like phpMyAdmin for managing your database. This section covers common database operations you can perform using WP-CLI:

Exporting a database

With WP-CLI, you can export your database as an SQL file. The exported file is saved in the root directory of your WordPress installation.

wp db export

Result: An SQL file is created in the root directory.

If the exported file has an ungainly name, you can rename it using the following command:

wp eval 'if ( rename( "unganglyfilename.sql", "newfilename.sql" ) ) { echo "File renamed successfully."; } else { echo "Failed to rename file."; }'

Input example:

wp eval 'if ( rename( "cilawawugo4504_gTr4kSXUsmJ9FNauVnPb-2024-11-17-9545b3f.sql", "network-db.sql" ) ) { echo "File renamed successfully."; } else { echo "Failed to rename file."; }'

Result: File cilawaw…nPb--9545b3f.sql is renamed to network-db.sql.

Downloading a database

To download the exported database file to your local machine, use the curl command.

curl <remote-url> -o <local-path>

Input example:

curl example.com/network-db.sql -o ~/Downloads/network-db.sql

Result: The file network-db.sql is downloaded to your local Downloads directory.

Uploading a database

You can upload a database file to the root directory of your Multisite installation using the scp command.

scp <local-path-to-file> <username>@<remote-server>:<remote-path>

Input example:

scp ~/Downloads/network-db.sql [email protected]:/var/www/example.com/public_html

Result: The file network-db.sql is uploaded to the root directory of your WordPress installation after authentication.

Importing a database

Before importing a database, you may need to reset your existing data tables.

  1. Reset data tables:
    wp db reset

    Result: All data tables in the database are emptied.

  2. Import the database:
    wp db import <file-name.sql>

    Input example:

    wp db import network-db.sql

    Result: The file network-db.sql populates the emptied data tables.

  3. Delete the imported SQL file:For security purposes, delete the SQL file after importing:
    rm <file-name.sql>

Practical examples

We can think of many commands that will speed and simplify your workflow. Here are three examples.  While some of these commands are more complex, they build upon simpler commands to carry out useful operations.

Install and activate plugins and regenerate thumbnails simultaneously.

This command loops through all sites in the network, installs and activates two plugins, and regenerates image thumbnails for each site.

wp site list --field=url | xargs -n1 -I % sh -c 'wp plugin activate <plugin slug> <plugin slug> --url=% && wp media regenerate --url=%'

Input example:

wp site list --field=url | xargs -n1 -I % sh -c 'wp plugin install akismet bbpress --activate --url=% && wp media regenerate --url=%'

Result: The plugins Akismet and BBPress are installed and activated across all sites, and image thumbnails are regenerated.

Adding a custom meta field for all users

This command loops through all sites, retrieves the list of users, and adds a custom meta field for each user.

wp site list --field=url | xargs -n1 -I % sh -c 'wp user list --fields=ID --url=% --format=csv | tail -n +2 | xargs -n1 -I {} wp user meta add {} <meta-key> <meta-value> --url=%'

Input example:

wp site list --field=url | xargs -n1 -I % sh -c 'wp user list --fields=ID --url=% --format=csv | tail -n +2 | xargs -n1 -I {} wp user meta add {} favorite_color "" --url=%'

Result: A custom meta field, favorite_color, is added for all users across all sites.

To surface the favorite_color field, you’ll need to use your functions.php file or create a custom plugin.

Converting a single site install to a multisite

WP-CLI makes it easy to convert a standalone WordPress site into a Multisite network.

wp core multisite-convert

Result: The single site is converted into a Multisite network.

Before conversion, make sure to deactivate all plugins.

After converting the site, you need to configure the network URLs in the wp-config.php file. You can choose between using subdomains (e.g., site.example.com) or subdirectories (e.g., example.com/site). Additionally, check the .htaccess file, as the URL rewrite rules (handled by the mod_rewrite module in Apache) may require manual updates to ensure your permalinks and site structure work correctly.

Summary

This guide highlights the power and flexibility of WP-CLI for managing WordPress Multisite environments, making it an essential tool for developers and administrators seeking efficiency and control. From handling plugins, users, and databases to performing advanced operations like converting single sites to Multisite, WP-CLI simplifies complex tasks with precision and speed.

Kinsta offers an invaluable and extensible WP-CLI tool that enables seamless management of WordPress Multisite networks. Whether you’re working on live or staging environments or using our local development tool, DevKinsta, WP-CLI is readily available to streamline your workflow.

Start creating sites, adding plugins, users, and more with WP CLI!

The post Working with WP CLI for WordPress Multisite appeared first on Kinsta®.

版权声明:
作者:dingding
链接:https://www.techfm.club/p/180522.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>