WP CLI is the command-line tool of choice when it comes to managing and administering tasks within WordPress. Combined with the power of regex (a sequence of characters defining a search pattern), it enables powerful search and replace functions.
WP CLI documentation on executing a search and replace on the database using regex can be confusing. Here’s a one liner that works and can eliminate some confusion. Feel free to tweak and play (on a sandbox install).
Table of Contents
Why Choose WP CLI For Search & Replace?
- Data-Integrity: Data within the WordPress database is serialized. Altering this data will break the database integrity.
- Serialized Data: WP CLI deserialization the data before altering it and serializes it again before saving it.
- Efficiency: Enables quick, efficient and precise operations.
- Flexibility: Tailors search-patterns to specific needs.
- Safety: Dry-Run allows you to test commands and gives verbose output before you decide to commit.
Prerequisites for Utilizing WP CLI & Regular Expressions
Before embarking on this task, you must ensure access to a WordPress installation and WP CLI. It is safer to perform these operations on a sandbox install to mitigate risks. See also: Download WP CLI Temporarily & Using With Custom PHP Versions
You also need to have some understanding of Regular Expressions.
Do not forget to replace the regex with your own.
This is the first thing you should try before trying something crude like replacing via PHP.
wp search-replace '<script.*?217bc9f0d28b2da070\.js.*?<\/script>' '' --all-tables --dry-run --report-changed-only --precise --regex --regex-delimiter='/'
Breakdown of What WP CLI Search Replace Command
–all-tables runs the search-replace on all WordPress tables in the database.
–dry-run only shows what will be changed without actually changing anything.
–report-changed-only reports changed fields only.
–precise forces the use of PHP (instead of SQL) which is more thorough, but slower.
–regex tells WP CLI to search using the regular-expression we provided.
–regex-delimiter sets the regular-expression delimiter to ‘/’ which is the standard way of using regular-expressions in PHP.
Safety With WP CLI & Regex
- Dry Run: Utilize the
--dry-run
option. - Backup: Do a quick database backup with
wp db export
. - Understanding: You can use online tools like RegExr 3 to understand your regex pattern.
Bonus:
Did you know you can deploy Malcure Advanced Edition en-mass? Check this: Deploying Malcure Advanced Edition With Cron, WP-CLI for Automatic Periodic Scans