Changing URLs in WordPress Database via Command Line

I am learning the art of a sysadmin is not so much knowing how to do something, but rather how to do something quicker via command line 🙂 I transferred a cPanel account the other day from one domain to a different domain, and I needed to update all the URLs across 3 or 4 different WordPress sites.  Traditional I would export the database, do a copy and paste in TextWrangler, then re-upload the SQL file. For four different WordPress sites that begins to get laborious. But then I remembered the trick Tim showed me when we were doing the UNLV migration a little while back. WordPress now has a command line interface (CLI) tool, and Tim showed me how to use it to do a find and replace on the database. You would need to be in the root directory of the WordPress site when running the following:

wp --allow-root search-replace 'jimgroom.net' 'jimgroom.com'

The above command would replace all instances of jimgroom.net in the WordPress database with jimgroom.com. I ran this command 4 times in about 5 seconds and more than 1000 URLs were instantly updated. It would have taken me 10-15 minutes minimum to exporting, find & replace, and then import the databases for 4 sites—and let’s face it, doing it in a few seconds firing off some command line code just makes me look more serious. Kinda like Timmmmyboy playing the sysdmin in Adam Croom’s Hair game 🙂

This entry was posted in sysadmin, WordPress. Bookmark the permalink.

2 Responses to Changing URLs in WordPress Database via Command Line

  1. Alan Levine says:

    That’s on my least of things to learn is mor WP-CLI. There is one gotchya with url changes; some theme options are serialized arrays where it stores also the length of the url string. In your case, changing .net to .com is safe but I had a client site that lost its theme settings because of this

    • Tim Owens says:

      wp-cli’s search and replace actually handle’s serialized data properly by reconfiguring the arrays. I’ve been burned by that in the past with other tools as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.