Simon Davies Digital ltd

The dangers of search and replace in WordPress

Posted by Simon Davies & filed under WordPress.

This week I learnt an important lesson when using Search and replace in WordPress. When I'm working on a site in development I have WordPress running on a dev domain so the client can view the website and make any changes via the dashboard. When the site is ready to go live I go about transferring the domain. To do this I also need to update any posts in WordPress that may contain the old dev domain to the new live one. To do this I use a plugin by Bueltge called Search and replace. This searches your database for a string of text and replaces it with another, which is perfect for replacing old dev URL's for live URL's I have used this numerous times in the past and never had any problems with it. The problem occurs when using widgets and more specially text widgets. If you have looked into how WordPress stores widgets in the database you will know that each registered widget has its own field in the wp_options table which contains a serialized array of each instance of that widget. To understand how the problem occurs we need to first understand how the serialize PHP function works. Lets have a look at a simple example of serialising a string.
echo serialize("foobar");
This would print s:6:"foobar"; The syntax is pretty simple, first the variable type which in this case is a string (s) then the variable length (6) and then the value ("foobar"). Here is a slightly more complex example serialising an array:
$array = array('foo', 'bar');

echo serialize($array);
Would print: a:2:{i:0;s:3:"foo";i:1;s:3:"bar";} The problem with Search and Replace lies with the variable length, if we had a url stored in an serialised array such as (s:22:"http://dev.example.com";) and then changed this to (s:22:"http://example.com";) the array would now be invalid as the string has changed but we haven't updated the string length. And more annoyingly if you were then to click on the Widgets page, WordPress would notice that there was an invalid entry in the database and over write this with a blank array, losing all your data! Unfortunately for me the last database backup I had was from the day before, so I learnt 2 valuable lessons that day. 1) Always backup a database before making any big changes and 2) be wary of Search and Replace especially when using Text Widgets UPDATE: Recently I have been using a script from interconnect/it that will search and replace serialised data as well.

Contact

Want to hear more about Mode and what we can do for your business or simply want to say hello, then get in touch.

+44 7846 400933
[email protected]