Search and Replace Localhost Domain in WordPress Database after Migration

Are you setting up a local development environment for an existing WordPress website, and imported a large database dump locally? You’ll need to replace your domain name with localhost in all its occurrences.

Are you working locally on the design and development of a WordPress site and are now ready to migrate it to a staging or live server? You’ll need to replace localhost with your domain name in the database.

The bare minimum you need to do to make the site operational on the new host, is to update your wp_options table with the new server value. You can easily do this with phpMyAdmin running a query like this:

UPDATE wp_options SET option_value = replace(option_value, ‘https://domain-to-be-replaced’, ‘http://current-installation-domain’);

Be sure to include the http and https as required in case you are migrating between an SSL enabled server and a non-secure one.

But, what if you need to update all your posts with new references? Good news: there are 3 ways to handle this.

1. The Old Fashioned Way: open your SQL dump with your code editor (i.e. Sublime Text), find and replace all occurrences, save, then import the database. This is the easiest way around. Just be sure to include the full domain names you need to replace, and then also check for http:// and https:// too if you’re migrating between a non-secure and an SSL enabled host.

2. The Nerd Way: open the terminal and use the WordPress Command Line to run a search and replace in the database.

i.e. To turn your production multisite database into a local dev database

$ wp search-replace –url=example.com example.com example.dev ‘wp_*options’ wp_blogs

For non multisite installation, remove wp_blogs. If you do not have the WP CLI installed, you probably don’t want to go all the way to make it work for this operation, so read on because the next solution might be the best route for you.

3. The GUI way: download this script from GitHub, it was built by Interconnect/it to search and replace on the WordPress MySQL database.

The script author recommends to rename the directory to some arbitrary hard-to-guess name for security reasons. Upload the folder in the root of your WordPress install, then open it in your browser (i.e. http://yourdomain.com/12340-your-secret-name/)

In the form that will appear, you will be able to enter the string you’re searching for, and then the replace string. Your MySQL details/login should already be populated. After entering your search and replace terms, scroll down and click “Update Details”, then do the “Dry Run” option first to preview the changes that will be applied to the database. If you are satisfied with the changes, click “Live Run”.

Comprehensive step-by-step instructions are available at the author’s website.

Important: for security reasons be sure to delete this directory from your server after you have finished using it

Source