I’m trying to use wordpress’ media upload popup in a custom plugin I’m working on.
So far everything worked, I was able to upload images and insert them into a field, but I have another field that requires a link to the uploaded pdf.
tb_show('', 'media-upload.php?type=image&TB_iframe=true;height=200');
window.send_to_editor = function(html) {
console.log(html);
console.log(jQuery('a', html));
console.log(jQuery('a', html).attr('href'));
console.log(jQuery('img', html));
console.log(jQuery('img', html).attr('src'));
imgurl = jQuery('a', html).attr('href');
current_upload.prev().val(imgurl);
tb_remove();
}
For an image this would be my output, which is right since it’s able to select the image source
<a href="http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM.png"><img src="http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM-300x221.png" alt="" title="Screen Shot 2012-06-20 at 12.15.52 PM" width="300" height="221" class="alignnone size-medium wp-image-49" /></a> to.js:54
[]
undefined
[
<img src="http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM-300x221.png" alt title="Screen Shot 2012-06-20 at 12.15.52 PM" width="300" height="221" class="alignnone size-medium wp-image-49">
]
http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM-300x221.png
But when I select a PDF I get this:
<a href='http://to.local/wp-content/uploads/2012/07/01-Mobile-Characteristics-and-Interaction-Design-Principles-Slides2.pdf'>01 Mobile Characteristics and Interaction Design Principles (Slides)</a> to.js:54
[]
undefined
[]
undefined
So I can’t figure out why jQuery(‘img’, html) works fine while jQuery(‘a’, html) doesn’t, while in both cases there is a link in the returned html.
Assuming
html = jQuery('<a href="http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM.png"><img src="http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM-300x221.png" alt="" title="Screen Shot 2012-06-20 at 12.15.52 PM" width="300" height="221" class="alignnone size-medium wp-image-49" /></a>');,htmlis the<a>element.jQuery('a', html)tries to select<a>within the children ofhtml, which returns no results as there are no<a>elements there.Since
<img>is a children of the<a>parent inhtml,jQuery('img', html)works.In your case, to get the
hrefattribute ofhtml, do this:(Remove the
jQuery()ifhtmlis already an jQuery object)