Replace Relative URLs without Manually Editing Every Post
When I first started EngageWP.com, I was toying with the idea of another name (WPEngage) and wasn’t sure whether I would end up switching before the content started developing any amount of popularity. The reason I was thinking of another name was because I tend to over-think things way too much. I utimately decided to keep EngageWP and am so happy I did because I love the name and WPEngage, now, just doesn’t sound right. However, my OCD prompted me to start using relative URLs throughout my posts to make a possible transition easier. Using relative URLs on my live blog was not very smart and just became a mess that needed to be worked out.
To fix it, I switched any relative URL in my widgets and other locations (templates, functions, etc.) to an absolute URL and all that was left was to edit the post content. I certainly did not want to manually search and replace any relative URL contained within my 70+ posts. Being a fan of SQL, I hopped over to Google to confirm the commands I needed to run to replace relative URLs in my post content. Interestingly, there was a post already written on this subject by Barry Wise. Barry also does a nice job explaining the difference between absolute and relative URLs in case you don’t already know.
Here’s the simple SQL statement that will replace any relative URL in your WordPress post content with (recommended) absolute URLs.
UPDATE `wp_posts` SET `post_content` = REPLACE(`post_content`, '<a href="/' , '<a href="http://yourdomain.com/');
This SQL statement is doing the following:
- Updating the wp_posts table (you may have a different prefix for this table). This is the table where your actual post content is saved.
- Replacing any string of
<a href="/
(the beginning of a relative URL) in the post_content column with<a href="yourdomain.com/
(an absolute URL)
Messing around with your website’s database is a dangerous thing if you don’t know what you’re doing. Always always always make sure to have an up-to-date backup before running any SQL commands against your database so it can be restored if something goes wrong.
Anders says
Hi I need to replace relative URLs with https on all tables what would the correct query be?
Neeraj bhandari says
Hey Ren,
Your tip solved my problem in a second. Thanks a lot
Richard Uren says
Hey Ren,
We just went live with a new site when we found many of the URLs in the imported content we loaded were wrong (140 Posts ! Gah !). Your handy tip solved the problem in a flash. Thanks 🙂
Cheers
Richard
Ren says
Hi, Richard. So glad to hear! Thanks for sharing. 🙂