WordPress Quick Tip: Search and Replace with WP-CLI

Moving WordPress sites can be a pain in the posterior. Code has to be moved, databases have to be moved, and those are the easy parts. If you are actually moving it to a new domain, or sub-domain, things get really tricky. Thankfully, there is a tool to help. Let’s take a look at wp-cli search-replace.

If you aren’t familiar with it yet, WP-CLI is the WordPress developer’s swiss army knife. That is if you could add new tools to an ever expanding swiss army knife and then still fit it in your pocket. WP-CLI is a command line tool for WordPress developers to help with everything from setting up to create a new plugin, to performing basic database operation.

One of the features that comes stock with WP-CLI is the search-replace command. As the title suggests, this is a way to search and replace things in your database. Things like domain names or URLS. This is the easiest example for most developers to understand but it can also be used to replace image names, or to help move your images to a CDN if you are handing it manually.

When moving your site from your development environment to your production environment, you may need a command like this.

wp search-replace 'http://example.dev' 'http://example.com'

Not sure if you got the parameters just right? add the --dry-run switch and WP-CLI will show you what it is going to do, but not actually make any of the changes.

The beautiful things about using WP-CLI’s search-replace command over say a simple SQL statement is that WP-CLI knows to scan your entire database, and WP-CLI knows how to unpack JSON payloads stored in your DB, perform the search and replace on them, and then if changed, re-pack them and update the database.

This is only one of the many things that WP-CLI can do for WordPress developers but it is probably the one most used. When you have your WordPress site setup on Pantheon, you know that moving your site from development to test or production is just a click of a button. Behind the scenes though, one of the steps we do is run WP-CLI’s search-replace to change all the instances of your development URL to either your test or production URL.

Check out WP-CLI today and watch how it changes how you approach admin tasks for WordPress.

Topics WordPress