Reputation: 975
I want to take any url on a page, mainly for the sake of fixing images that aren't displaying, and change it from relative to absolute, if it's relative.
Example:
From <img src="/folder/folder/image.jpg" />
To <img src="http://<?php echo get_option('domain'); ?>/folder/folder/image.jpg" />
Since the domain portion I'll be inserting is a PHP snippet, whichever approach is best for that is more so desired. Thanks.
Upvotes: 1
Views: 1980
Reputation: 2344
With JQuery you could use the .attr() to change the src string. Without an ID attribute it could become difficult trying to capture the correct img tags. You would have to check each src string for "www." to see if there is already a site reference before appending the current site.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/lib/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("img").each(function(){
if($(this).prop("src").toLowerCase().indexof("www.") != -1){
$(this).attr('src', document.domain + $(this).prop("src"));
}
)};
</script>
I think the hardest part is identifying which img tags need to be changed.
Upvotes: 0
Reputation: 57114
use a regular expression for this:
$text = '<img src="abc" /> asiodn <img src="dev" />'; //e.g.
$regex = '/<img src="([^https?:\/\/][^"]*)" \/>/';
$result = preg_replace($regex, '<img src="http://' . get_option('domain') . '$1" />', $text);
this should fix all relative urls in image src
http://codepad.viper-7.com/TsHGbE
Upvotes: 0
Reputation: 74420
Using jquery:
$(function () {
$('img').each(function () {
if (this.src.indexOf('http://') === -1) this.src = "http://mysite.com" + this.src;
});
});
Upvotes: 1
Reputation: 1295
You can just get all the img elements and change the src to document.url + img.src. Should be pretty simple, in JavaScript. I think the bigger question here is why are you having trouble with the relative URL? If you want to load images dynamically from a different domain or something like that then yes that is fine.
If you need to do this on page load then you are better off building the url server side in whatever you are using to render your html.
More information and code examples on how to do it in JS here. Getting an absolute URL from a relative one. (IE6 issue)
Upvotes: 4