Using the WP-CLI to Perform a Search and Replace

WordPress Command Line Interface

WordPress hardcodes your site’s domain name into the database for such things as image, link, and page URLs. This can be a problem when you migrate the site to another domain name because clicking on links will redirect back to the old site. In this instance you must update the URLs in your database in order for your site to function correctly.

The WP-CLI otherwise known as the WordPress Command Line Interface makes managing your WordPress website(s) simple if you are somewhat fluent in working through the command line interface.

For example, the WP-CLI command search-replace will search for a string of data that you specify and replace it with another. This is especially useful when you need to change a website URL / domain. In this guide, you will learn how to use the WP-CLI command search-replace to replace an old URL with a new URL.

Old URL to New URL

WP-CLI’s search-replace command replaces the URL configured for your website, should you decide to change the domain. For example, if you built a website on old-domain you can use this command to replace your database details to use new-domain

Step 1. Log into your cPanel account and look for Terminal under ADVANCED

If this is your first time accessing Terminal you’ll receive a warning message and need to click the blue I understand and want to proceed. button.

You will now see a black screen which is the interface for Terminal. The part before the @ symbol is your cPanel username. The part after the @ symbol is the name of the server your hosting account is installed on.

Step 2. Use the cd command to switch to the document root directory of your website. For example, if your site was installed in public_html you would type cd public_html If the site is contained within a subdirectory inside public_html you would type cd public_html/my_website

Be sure to replace public_html/my_website with the actual path to the document root directory of your website.

Step 3. Run the following command (replacing old-domain and new-domain with the actual domains you wish to find and replace)…

wp search-replace http://old-domain http://new-domain --dry-run

The resulting output displays the details, including tables and how many replacements are being made.

Once you have verified the replacements are correct, you can proceed to run the following command to have the database updated accordingly…

wp search-replace http://old-domain http://new-domain

1 Like