Ahmed Ebraheem
Ahmed Ebraheem

Reputation: 63

Change only the site url in image source url

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?

Upvotes: 1

Views: 699

Answers (2)

Ahmed Ebraheem
Ahmed Ebraheem

Reputation: 63

I make it by using str_replace
http://php.net/str_replace

$old_src = 'http://domain.com/theme/wp-content/uploads/2014/12/image.jpg';
$old_url = 'http://domain.com/theme/';
$new_url = 'http://new-domain.com/new-theme/';

$new_src = str_replace($old_url, $new_url, $old_src ).'<br/>';
echo $new_src;

Upvotes: 2

Joe Czucha
Joe Czucha

Reputation: 4295

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:

 http://domain.com/theme/

with

 http://new-domain.com/new-theme/

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.

Upvotes: 1

Related Questions