Taming Media Upload in Your Theme or Plugin

Posted on Friday, April 8th, 2011

And changing that pesky “Insert Into Post” button

For all you WordPress developers out there, here’s some good news:

You CAN use the built-in WordPress Media Upload functionality in your plugin or theme.  I can’t take credit for figuring THAT out – that goes to Matt with His post here. It’s a glorious thing.

But I had three more challenges to overcome:

Challenge #1: Changing the “Insert Into Post” Button

To do that, I had to hack through the Dom to finally figure out how to address the button with jQuery.  Then, once I figured THAT out, it seemed every time you clicked one of the tabs (“From URL”, “From Gallery”, etc), things changed.  So, my solution – while not elegant – does get the job done.  And here it is (just drop it into the “click” function):

tbframe_interval = setInterval(function() {jQuery('#TB_iframeContent').contents().find('.savesend .button').val('Use This Image');}, 2000);

Yep, an interval. Every 2 seconds, so not overly obnoxious on the resources. And you can change the “Use This Image” to read whatever you like.

To keep it clean, I also added in a clear interval on the “send_to_editor” function:


Challenge #2: Making it Play Nice on the Add/Edit Post (or Page) Pages

This also I cannot take full credit for – that goes to Frosty in his post here. But, there were some details missed, so I had to adjust his solution.

For example, once you used your Custom “Upload Media” button, if you went and tried to upload media to your post, it would post to your custom form, not to the post. So, I just added a simple line of code to clear the flag to the “Send_to_editor” function”:

formfield = "";

And that’s it!

Challenge #3: Using Media Upload for Multiple Input Boxes

As part of a theme I was developing, I needed to allow someone to set an image for six different input boxes.

That took some creativity, but it all worked together nicely. By assigning using some classes (so I could have jQuery iterate over each element I wanted), and some careful input id’s to associate the buttons and input boxes, and then writing a couple of lines of javascript to grab the id, parse it, and associate it with the right input box, I was off and running.

If anyone’s interested in the “bundled” code all together, let me know and I’ll gladly post it.

Leave a Reply


comment on this post »

No comments on this post yet.