How can I change the site url in an image source url to a new site url, something like this:
Original Image: http://domain.com/theme/wp-content/uploads/2014/12/image.jpg
After Replace: http://new-domain.com/new-theme/wp-content/uploads/2014/12/image.jpg
How can I do this using PHP?
I make it by using str_replace
http://php.net/str_replace
The easiest way to make this change is at a database level.
I do this kind of thing all the time when I deploy a site and I need to change the staging domain (staging.test.com) to the live domain (test.com). Generally, WordPress generally uses the WP_SITEURL set in wp-config.php to determine asset paths but this is not the case for images.
I use the Search and Replace for WordPress databases script and it’s pretty solid, just replace:
with
and you should be good to go…
Alternatively, if you’re not moving a site then you can change specific instances in the database – for this I’d recommend using a tool like Navicat (for OSX) as this can perform search/replace operations on specific tables.