Skip navigation

Search and Replace in WordPress MySQL Database

There are times when you must enter the WordPress MySQL database to search and replace some content. If you don’t have to do this, then DO NOT DO THIS. If you have to do this, then your head should be examined carefully, opened up and inspected for programming errors, and then you may proceed with due and dilligent care.

When might this insanity occur? This overwhelming need to destroy your blog? Most commonly it happens when you change domain or email addresses and need to make sure that all the old links are gone, replaced with the new links. Or if you have just imported massive content into the database and you’ve discovered a recurring boo boo across the majority of posts.

Reason why NOT to do this. First, because it can and will destroy your blog and database if used incorrectly. Second, if the item you wish to search and replace is found in 20 or fewer posts, fix them manually. Much less invasive and destructive.

Third, what you search for MUST be unique. It must only be found at the point where you want the change made. Searching for a domain name or email address is pretty unique content, but a group of words or code that can be found in other places will search and replace ALL of the code, screwing up everything. For example, if you search and replace every “there” for a “their”, you will end up with “their’s no place like home” or “theirfore”. I once made the mistake of deciding that “website” was to be spelled consistently on my site as “web site”. A massive search and replace turned links with the word “website” into “web%20site” which broke all such links. Do you know how many people have the word “website” in their links? Too many, and I think I linked to all of them.

If you are still willing to go forward with this amazingly stupid and risky thing to do, here are the final warnings and instructions.

BE VERY CAREFUL WITH THIS. IT WILL HURT.

Should I say, “don’t do this at home”, too? You get the point.

1. BACKUP YOUR DATABASE FIRST.

2. From within PHPMyAdmin, open your database.

3. Check the names of the table and field holding the information you want to change. For WordPress users, the most common search and replace is done on the content so we’ll use the wp-posts table and the post-content field within that table.

4. To search and replace text within your wp-posts table and the post-content field, click on the SQL tab and enter the following with the exact item you want to search for in the third line, and what you want to replace it with in the last line.

UPDATE wp_posts SET post_content = REPLACE (
post_content,
'Item to replace here',
'Replacement text here');

5. Making sure that the ONLY parts you change are within the little single quotes.

6. Make sure EVERYTHING is spelled right and that the names of wp-posts and post_content, or whatever table and fields you are using, match the table and field within your database. Make sure that post_content is listed twice and that they match.

4. When you are sure, and you have made arrangements to have your body and brain donated to science when your brain explodes because this destroys everything in your database (okay, not really, but I’m impressing upon you the care you have to take with this – got it? Can I stop now? Good.), then click the GO or APPLY or whatever the DO IT NOW button looks like in your version of PHPMyAdmin.

5. It will then go through your database’s wp_posts table in the post_content field looking for the first line in the search and replace command, and replacing it with the second line.

6. The results will tell you how many records were changed. Let’s hope it’s the number you anticipated. If not, then restore your backup and start over.

While I jest about this process, it is a very serious and risky thing to do, but it is also very helpful. When setting up a test WordPress site, I often want all the pings closed. When I move a test site out to the public, pings need to be turned back on. To turn all the pings back on for every post and Page within my site, I used the following shortcut version of the above search and replace command:

UPDATE wp_posts SET ping_status="open";

If the ping_status was “closed”, it was now “open” and if it was blank, it was also now “open”. I then went through the Pages for my “About”, “Contact”, and other posts and Pages I didn’t want open to comments or pings and turned them off manually.

Again, I never do this without a backup, and even I have screwed this up, so if I can do it, I’m sure you will, too. ;-)

39 Comments

  1. Michael Hessling
    Posted January 10, 2006 at 3:10 pm | Permalink

    This post is very useful. However, is there any way to grab text like:

    onclick="window.open('/photo.html?/wp-photos/photo123.jpg','','resizeable=1,width=500,height=450'); return false"

    where “photo123.jpg” changes from post to post?

    I don’t relish the thought of going through 500+ posts and stripping out the bad javascript. :(

  2. Posted January 10, 2006 at 5:03 pm | Permalink

    If the image file name is in the javascript, you are screwed. Yes, you can delete the redundant javascript, but the parts with the image file that is different for every reference, you are out of luck.

    I’m sure there is someone out there, not me, that would help you create a list of the images and write a script that would search and replace the javascript, inserting each file name as it goes, but that’s beyond me.

    Been there, done that, too many times, so unless you have a seriously swift PHP scripting buddy, get to work. It takes much longer to whine about it then to manually fix it. Trust me. I’m an expert on whining over botched code. ;-)

  3. Michael Hessling
    Posted January 12, 2006 at 11:26 am | Permalink

    So … use PHP to write an if-else loop? I’ll do that; that’s more interesting than either whining or the manual fix. :)

  4. Shawna
    Posted February 17, 2006 at 5:55 pm | Permalink

    I’m having a bit of a problem attempting to replace something. It’s actually with a PHPBB table. I have random  ’s all over 200+ posts, but phpMyAdmin isn’t liking the & in the command. It will work if I just use  , but that leaves me with &’s all over the place.

    Is there a workaround for this?

    This is what I’m trying:
    UPDATE gecko_fl_phpbb_posts_text SET post_text = REPLACE (post_text,” ”,”");

  5. Posted February 17, 2006 at 7:43 pm | Permalink

    I’m not sure what the correct replacement for non-breaking spaces would be. You would think that that   code would do it. I don’t understand why it leaves ampersands behind. Sorry. I’m not even close to a MySQL expert. Keep looking and if you find a solution, would you let me know?

  6. Posted February 24, 2006 at 10:39 am | Permalink

    After looking through the actual posts saved in the tables, I realized that when I was converting it had replaced the actual ampersand on the   with &. Like this: & amp;nbsp. Then I did a search and replace on that and it fixed everything :)

  7. Posted February 24, 2006 at 1:32 pm | Permalink

    It got it. ;-) And thanks for the tip! Character entities are a pain.

  8. Posted November 18, 2006 at 4:16 pm | Permalink

    Thanks for the post. It helped me a bunch with a silly string that got stuck in my data on export. I used it on MT, but it worked well.

    Thanks

  9. Posted August 6, 2007 at 7:12 am | Permalink

    Damn that was easy! Thanks for the morons guide to modifying a WordPress database :)

  10. Posted October 5, 2007 at 12:47 pm | Permalink

    mainly posting this for myself, so i don’t forget: some versions require backticks around the table_field you’re replacing. my query is like:

    UPDATE wp_posts SET `guid` = REPLACE (
    `guid`,
    'http://old.domain',
    'http://new.domain');

  11. Posted October 5, 2007 at 1:28 pm | Permalink

    They aren’t “tickbacks” but apostrophes. Backticks or “ticks” are character codes created in word processing programs from the key found next to the 1 on English keyboards. They are not recognized elsewhere, so please only use quote marks and apostrophes. Ticks might bork your code.

    The use of quotes around these areas must be new for new versions of MySQL…checking…nope. The “field” which is the first variable, does not have to be in apostrophes. So the correct layout is mentioned about, and using your example, it should be:

    UPDATE wp_posts SET guid = REPLACE (
    guid,
    'http://old.domain',
    'http://new.domain');

    Where did you figure it out that it needed apostrophe marks around the field name?

  12. Posted October 5, 2007 at 4:12 pm | Permalink

    that was in PHPMyAdmin, so maybe it’s specific to that. and no, those are backticks. it requires backticks on the table_field, and apostrophes on the values.

  13. Posted October 6, 2007 at 10:21 am | Permalink

    Really odd, cuz I’ve been using this for years in PHPMyAdmin, and have never used backticks or apostrophes on field table names. I’d love to know where you found that as my research continues to show that it isn’t necessary. Glad it works for you, and I’ll keep looking for support documentation on this. Very odd.

  14. Posted October 8, 2007 at 10:47 am | Permalink

    i “found” it, because when i ran the command without the backticks, it kept replacing old.domain with guid. The version of PMA (2.8.1, part of XAMPP) sometimes has a little “fields” suggestion box in the top right. clicking on those fields added the backticks. when i ran the query with backticks, it replaced with the proper values.

  15. marv
    Posted October 19, 2007 at 10:37 pm | Permalink

    Thank you, for the sql update query and for the incessant cautions.

  16. Posted October 20, 2007 at 8:36 am | Permalink

    I’ve been looking for a safe way to do this for a while!

    Now I can batch edit my anime videos on my site with ease.

  17. Posted December 23, 2007 at 9:32 pm | Permalink

    Thanks Lorelle :)
    I hunted high and low for how to do this and none of the solutions I found worked at all. But I could distinctly remember reading about this very topic on here so did a search for “lorelle mysql search and replace” and low and behold I found the original post and sure enough it worked perfect :)

  18. Posted January 7, 2008 at 11:04 am | Permalink

    I changed my theme so backgrounds are blue instead of white, and I embedded adsense with a white background into the middle of each post.

    Adsense has since come out with a better mechanism so I can make changes inside their interface and the colors will auto-update. However I have over 600 posts to swap the old adsense code out for the new.

    My find and replace will involve the fairly large chunk of adsense code. Two questions, one is I know to escape the periods in the find/old code, but do I need to escape the periods in the replace/new code also? Also, do you think I will have better or worse luck in my search/replace operation because I am searching for such a large and unique chunk of code?

  19. Posted January 7, 2008 at 12:26 pm | Permalink

    @ Joe Vandal:

    You know there are Plugins that will help you put your ads in your posts and blog without doing this manually? Who Sees Ads WordPress Plugin by PlanetOzh is also very popular.

    As for your question, search and replace what needs to be changed. Leave what doesn’t. Larger, UNIQUE chunks are better than small, not unique chunks, but size doesn’t matter. Uniqueness does. You don’t want to search and replace things that will mess up other areas in your database. BACKUP first. This is not to be done lightly.

    I’d replace all of the code with a Plugin so you don’t have to do this again.

    As for ads within blog posts, that’s another issue and most people find it annoying and that it biases them against the blog. Just information you might want to know.

  20. Posted February 8, 2008 at 6:45 pm | Permalink

    thanks!! very usefull for my blog… u’re my hero!!

  21. Posted February 13, 2008 at 1:10 am | Permalink

    Lorelle – Love your blog – THANKS! I amsol and struggling. I have a blog that is remorelty hosted, Oploaded the files to godaddy for me and made some changes to the blog. Worked fine. I then tried to copy it to another url at godaddy. I followed instructions re FTP’ing the files to my hardrove and made 1 mistake – I never backed up the database befopre changing the URL. Of course the moment I changed the URL – I could no longer get into wordpress or the blog. I got all the files and the changeed database into the new locatiobn and restpored everything to the old one. Now I cannot get to either blog. I have checked and changed the URL in the database and the config file. This is the message I get:
    “Error establishing a database connection”

    I have checked these and they seem to be fine. What options can you think of and is there anything I cando? Thanks.

  22. Posted February 13, 2008 at 5:59 pm | Permalink

    @ Gary:

    Ouch. If you can edit the database, go in and manually change the information. After that, your best help on this is the WordPress Support Forums. They will be able to help you with the specifics.

    Also, I deleted the error information that revealed private information about your blog’s server. DO NOT publish that information anywhere as it can invite hackers.

  23. Posted February 17, 2008 at 8:33 pm | Permalink

    Actually, I am trying to set up a new blog and try to drop all the default database and try to replace my old blog’s database which has already posts, alot post actually. But I am having not to set up right. When tried to drop the default database then access my site, wordpress then goes installing again thus, creating the default database. I have imported my blog’s old database on it but it doesnt uses it. How to fix this one?? Please help

  24. Posted February 17, 2008 at 8:39 pm | Permalink

    @ seocontest2008:

    You need to get help via the WordPress Support Forum.

  25. Posted April 5, 2008 at 3:26 pm | Permalink

    Thanks Lorelle! This is so easy (if you’re used to working with databases) but you saved me soooo much time in figuring out the statement. Thanks!! :)

  26. Mad Dog
    Posted July 11, 2008 at 10:15 am | Permalink

    Have you heard of a plug-in that will strip out specified HTML code tags from posts? I set up a blog for a client who, despite my instructions, created lots of posts by pasting, which included and tags that are overriding the CSS. It would be nice to be able to either tell WP to ignore those tags in posts or to strip them out of the db, but unfortunately they’re all different so your method won’t work. Any idea?

    THANKS!

  27. Posted July 11, 2008 at 3:25 pm | Permalink

    @ Mad Dog:

    The wp-includes/kses.php file in WordPress contains the commands to strip out codes from posts. You can add or subtract code within there to remove things manually, without the use of a Plugin. There may be Plugins that handle this through the Administration Panels, but I don’t know of one.

  28. Posted July 15, 2008 at 12:45 pm | Permalink

    THANK YOU!!! I just upgraded my blog’s lightbox plugin from an older version to Lightbox2 and needed a way to update all the image code entries in my posts. I was going through each of them slowly and cursing myself for using so many images when I decided to search for someone way smarter about SQL databases than I am.

    I appreciate the time you took to create such a useful and explanatory post on the subject. You saved me a lot of tedious work!

    :-)

  29. Posted November 17, 2008 at 2:19 pm | Permalink

    You rock!! Thanks for saving me a ton of searching. My issue was left over [tag][/tag] tags from the Ulimate Tag Warrior after upgrading to 2.6.3.

    Thanks again!

  30. Posted December 3, 2008 at 7:46 am | Permalink

    It worked for me, yay !

    My sincere thanks for helping me solve an annoying problem, I am deeply grateful, Lorelle :)

  31. Posted January 13, 2009 at 7:43 am | Permalink

    I’ve been trying to clean up some badly coded pages. I need to replace/remove markup like fonts tags. I’ve tried to use wildcards with mysql:

    UPDATE wp_posts SET post_content = REPLACE (post_content,”,”);

    with no luck. Any advice would be much appreciated! Thanks for your time.

  32. Posted January 13, 2009 at 7:46 am | Permalink

    BTW, I’ve also tried:

    UPDATE wp_posts SET post_content = ” where post_content like ”

    No luck. Thanks

  33. Posted January 27, 2009 at 2:24 pm | Permalink

    Thank you so much for this post! I just moved my blog from one address to another, and I needed to update all of the internal linking on my site. It was done in a second, thanks to this guide! So thanks! :)

  34. Posted February 1, 2009 at 7:55 am | Permalink

    Thank you! Saved me hours of work! and saved 7 years of blogging! ;)

  35. NasMobile
    Posted February 21, 2009 at 3:23 am | Permalink

    Great post. I would add one check before No. 4. Run a select statement to see what fields you are changing before changing them. Something like:

    SELECT POST_CONTENT FROM WP_POSTS WHERE POST_CONTENT LIKE ‘Item to replace here’
    (NB: This might not be ‘pure’ MySQL statement – but I’m sure it would work in same was SQLServer).

    The ‘where’ clause must be the same as the clause in the update statement in No. 4.

    If this returns more values than you expect – DO NOT run No. 4. Fine tune, the select statement where clause e.g. ‘Item to replace here – this is better’.

    When you’re happy, adjust the No. 4 update statement:

    UPDATE wp_posts SET post_content = REPLACE (
    post_content,
    ‘Item to replace here – this is better’,
    ‘Replacement text here’);

    As you say Lorelle – do not touch this if you don’t know anything about MySQL.

    Goodluck. ( …… and ‘Just (don’t) do it’ ….. if you have any doubts – get the experts to take care of it for you!)

  36. Posted April 21, 2009 at 2:55 pm | Permalink

    VERY THANKS!

    WORKS FINE!

    you saved my life ;D

  37. George
    Posted June 29, 2009 at 4:00 am | Permalink

    Hi!

    I just made a big mistake! I had unistall wordpress from root!
    So:
    - I have database
    - I have all files in root

    How can I recover connection between database and public_html folder?

    Thanks!

  38. Posted July 14, 2009 at 11:23 am | Permalink

    Great tip, thanks very much! When I moved my wordpress stuff to a subdirectory, all my images broke because wp-content wasn’t in the right place any more.
    Cheers!

  39. Note
    Posted October 7, 2009 at 7:46 am | Permalink

    Thank you, I’m looking for this query


18 Trackbacks/Pingbacks

  1. [...] If there are many 404 Errors to a particular post, you can do a search and replace in your WordPress database, but be very careful. [...]

  2. [...] Att få exotiska tecken rätt var knepigare. Testade den här metoden för att konvertera ISO 8859-1 till UTF-8, men det funkade inget vidare. I slutändan valde jag att söka och ersätta i både inlägg och kommentarer. Tog lite tid, men det gick. Den som till skillnad från mig kan PHP/SQL skulle säkert kunna knåpa ihop ett skript. [...]

  3. [...] A “one question driven” purpose is the attempt to find a solution to one subject. For example, if you want to figure out how to how to search and replace in a MySQL database table, and the answer you get that helps you the most is the answer you need. [...]

  4. [...] Search and Replace in WordPress MySQL Database [...]

  5. [...] Upon trying to achieve XHTML 1.0 Strict, one of the thing i found out that i had been doing wrong all this while is that i put target=”_blank” HTML tag in most of my post link, this is not a valid XHTML for Strict and it won’t pass the validation, but i had been doing this since the very first day i blog! It will be troublesome if i’m going to search for every post and take away the target=”_blank”!! So i guess the only way to do this easily is by using the MySQL query, i went to Google around and found this very useful SQL query in Lorelle’s blog. [...]

  6. [...] Levar várias surras diárias da minha falta do php, do .htaccess, do próprio WordPress e até edição de MySQL “na unha”… [...]

  7. [...] seems that comments are sometimes not converted correctly, although everything else is. Normally, find and replace in MySQL databases is frowned upon, but because the gibberish is so unique (sorry to those who type entirely in gibberish), it is a [...]

  8. [...] Just do a search for the filename (ie. “smilie.jpg”) and edit the post to the new file location. You can do this right in WordPress admin area (under Manage) or use the blog’s search box. I didn’t have much post editing to do (makes me wonder what the heck I have those files uploaded for), but if your job is a big one you may prefer doing a database search and replace. [...]

  9. [...] the audio player code from <mp3> </mp3> to <audio: > using the Search and Replace in SQL database code as posted by Lorelle. I didn’t like the MP3-O-Matic player –with large files, it didn’t seem to [...]

  10. [...] http://lorelle.wordpress.com/2005/12/01/search-and-replace-in-wordpress-mysql-database/ [...]

  11. [...] Methode wurde z.B. von Lorelle schon beschrieben, basiert eigentlich auf einfachen MySQL-Befehlen ähnlich denen die WordPress [...]

  12. [...] very scary that you should do with great care (if at all)! Lorelle (WordPress guru) posted about search and replace in your WP database. I’ve used this before when I’ve decided to change some class names and didn’t want to go through [...]

  13. [...] ידעתי שעם קצת נבירה ברשת אמצא פתרון פשוט יחסית לעדכן את כל הקישורים באופן אוטומטי. אולי גם יש תוסף וורדפרס שעושה את העבודה. לבסוף חיפשתי ומצאתי את הפוסט הבא: “Search and Replace in WordpPress MySQL Database”. [...]

  14. [...] on WordPress came through again with her post about doing just what I needed. The solution was a simple UPDATE query on the wp_posts MySQL table. [...]

  15. [...]I recently migrated a blog from Blogger to WordPress and I think the following will help you [...]

  16. [...] are quicker ways of replacing links I’m told but I got scared and did it [...]

  17. [...] ידעתי שלאחר קצת נבירה ברשת (ככתוב google is your friend) אמצא פתרון פשוט יחסית לעדכן את כל הקישורים באופן אוטומטי ואולי גם אמצא תוסף וורדפרס שיעשה את העבודה. לבסוף מצאתי את הפוסט הבא: “Search and Replace in WordpPress MySQL Database”. [...]

  18. [...] found this great post at Lorelle’s blog about how to do terrifying scary dangerous stuff to your WordPress [...]

Post a Comment

Your email is never published nor shared.