Find and replace domain name on the fly?

Please read this carefully as it is not what you might be expecting.

I’m building my site in a development sub domain. I don’t want to have to go through the complications of running find and replace plugins after moving the site to the live area (as this can often go wrong on some serialized data).

Read More

I want to enter the urls into pages as they’re going to be on the live site (they need to be absolute URLs for the RSS feeds. So I need a method with PHP or Javascript to find and replace http://mysite.com with http://dev.mysite.com on the output pages. This way I can still test and preview the site and when it comes to going live I just have to uncomment that code. I’m not worried about the URL in the settings as that is always easy to change.

I hope that makes sense.

Thanks.

Related posts

Leave a Reply

4 comments

  1. I use these two defines in my wp-config.php file:

    define('WP_HOME', 'http://dev.mysite.com');
    define('WP_SITEURL', 'http://dev.mysite.com');
    

    Mind the trailing slash (or rather, the lack thereof), else you’ll get permalink bugs.

    Also note that they’ll actually get used as is if you insert images and so forth when adding content.

  2. This is not the direct answer to your need, but if you were going to switch subdomains, you should have created the links, images, etc. without the domain in them. You should have added a filter to remove the domain. Then you would have root absolute links beginning with ‘/’ not ‘http://www.domain.com/’.

    Here’s a start on how to make permalink root relative.

    But you will need to also run this function when you save your content (via a hook) in the administration, so you can strip the absolute links and make them root relative.

  3. Indeed this is not as I would expect. I am used to doing this statically. With that technique, aside from changing the DEFINEs in wp-config.php you’ll have to search/replace the entries in the database. To do this, just take a MySQL dump and run the following script with something like script.sh dump.sql > new_dump.sql. Load newdump.sql into the DB and you should be good to go.

    #!/bin/sed -f
    s/'([^']*)old.domain.com([^']*)'/'1new.domain.com2'/g
    

    You could try using the above regex in a preg_replace() to do this on the fly, but you might run into issues.