95 responses to “How To Integrate the WordPress Media Upload Box Into Your Meta Boxes”

  1. Luke

    Great Dimas! I’ve briefly tested and so far it works like a champ. Very nice work.

  2. leon

    great work Dimas , and great class but media upload have an error with multifields every field take the same value

  3. leon

    thanks Dimas your great .. keep it up

  4. pixenjoy

    Thank you again Dimas,

    I waited this feature for a long time and it will be very useful for everybody i’m sure 🙂

    I will test this uploader as soon as possible and give you feedback if i see a bug.

  5. pixenjoy

    I implemented the media upload class to my project by remplacing a simple input file by the uploader. Every things work well in the backoffice. However on the front, my data don’t display anymore.

    Do i need to change something in my template too ?

    The code in my back_metabox.php file:

    setGroupName('img-n'.$mb->get_the_index())->setInsertButtonLabel(__('Insert the url image in the field','aeronef')); ?>
    getField(array('name'=>$mb->get_the_name('imgUrl'),'value'=>$mb->get_the_value('imgUrl'))); ?>
    getButton(); ?>

    The code in my front_template.php file:

    global $custom_metabox_slider;
    $custom_metabox_slider->the_meta();
    ?>
    have_fields('slide')) { ?>

    <img src="the_value('imgUrl'); ?>">

    get_the_value('slideCaption')!='') { ?>

    the_value('slideCaption') ?>

    $custom_metabox_slider->the_value(‘slideCaption’) display but not the image : $custom_metabox_slider->the_value(‘imgUrl’);

  6. pixenjoy

    Sorry, it seems there is some problem with the markup in my prev. comment. My code is not fully displayed ...

  7. pixenjoy

    Hello Dimas,

    This is back_metabox.php (work well)
    https://gist.github.com/913221

    This is front_template.php (baseline display but not imgUrl data)
    https://gist.github.com/913217

    When imgUrl was a simple input field it display.

  8. leon

    bug again Dimas with multifields it’s like duplication error watch this
    goo.gl/7qooY

    and watch this another error
    goo.gl/Oo3Br

    best regards

  9. leon

    @Dimas Confirmed i use WPAlchemy 1.4.5 , release date : 6/4/2011

  10. Dameian

    Hi Dimas!

    Thanks for this. I owe you a few hundred beers and/or teas and/or coffees for making my life 100x easier.

    I wanted to contribute something that I’ve personally found very useful over the past couple of days while building a custom portfolio for a photographer. I found myself longing for the actual attachment ID, plus I wanted to populate a preview area so the client can see the image she just put in her portfolio. So around line 325 of MediaAccess.php I added the following:

    http://pastebin.com/SLWhkbnm

    Hopefully others will find this equally useful since it opens a whole new level of media management goodness via AJAX and the various built-in WP image manipulation functions.

    Cheers!

  11. pixenjoy

    Dimas,

    Yes, i see an imgUrl value in my wp_metadata table. This is a phpmyadmin screenshot of what i see in the meta_value field : http://www.pixenjoy.com/documents/screenshot.png

  12. leon

    any solution for my problem ?

  13. pixenjoy

    I put the var_dump() just before the “while” as you can see here : https://gist.github.com/913217

    And yes, i’ve got some output … imgUrl is in there : http://www.pixenjoy.com/documents/screenshot2.png

  14. pixenjoy

    Yes, img src is empty in my source code: http://www.pixenjoy.com/documents/screenshot3.png

    But

    http://localhost/public/wordpress/wp-content/uploads/2011/03/background4-300x194.jpg

    display my image in the browser.

  15. Dameian

    For anyone using WP Alchemy + the media uploader helper to on custom post types… I just wanted to mention this in case someone else hits the same wall I just did:

    If using custom post types and you do not have/want/need the visual editor capability enabled for that custom post type, you will lose the the ability to insert uploaded images. The button in the media manager window simply won’t be there for images uploaded through your custom post type.

    To get around this, what you can do is enable the editor capability when setting up the custom post type, then just add this to a css file that only loads when editing that particular post type:

    #postdivrich {
    display: none;
    }

    Not ideal, but it works.

    This may also be useful. Here is the conditional code I use to limit the loading of css to my custom post type editing page(s) so you don’t make every visual editor disappear:

    http://pastebin.com/3crj3027

  16. leon

    @Dameian in the WpALchemy it’s attr call hide_editor if you set it true the editor will gone and the insert button will come 🙂

  17. Dameian

    @leon Hah! Yeah. I had a bit of a headsmacking moment last night when I ran across that while looking through all the functions for something unrelated.

  18. pixenjoy

    I’ve found the bug ! Your code is ok Dimas, the error was in my script.
    Sorry to wasted your time.

  19. pixenjoy

    Hello Dimas,

    I would like to translate the “Add Media” button label with the php gettext functions but this label is a string in your MediaAcces.php file.

    It could be great to be able to translate this label in other languages in your next release.

  20. Bill

    Hi, is there a way to have a field in a meta box that accepts a single file upload? I’d for my users to be able to attach/upload a resume to a post. One resume per post. I’d like it to be a PDF file, too. But, I am not sure how I’d do this.

    If possible, I’d like to avoid exposing the user to the media gallery…

    thanks!

  21. Pietro

    Hi, there is no example code? It’s a little bit difficult read/copy the code in the youtube video 🙂 Tnx

  22. John Westbroek

    First of all, thanks for the MetaBox PHP class, it’s a real time-saver and hasn’t let me down so far.

    I’m running into a few problems using the MediaAccess class. When using it with regular posts it works fine but on Custom Post Types the “Insert” button doesn’t show up in the MediaUpload-box and is replaced by the original “Insert this” button (which doesn’t work). Also on PDF-files no button is showing at all. Could you help with this?

  23. shawn

    I saw the comment about the media preview images in the admin from pastebin, but I don’t see the code in the mediaaccess.php file.
    http://pastebin.com/SLWhkbnm

    I’ve tried adding it in myself, but keep getting it wrong.

    Any chance you could provide a modified vs. of mediaaccess that properly includes the image preview?

    love the script!

  24. pixenjoy

    Hello,

    Just a note : I use the theme-check plugin to test my theme and make sure it’s up to spec with the latest WP theme review standards.

    And when i ckeck my theme, this message display :


    WARNING: Found eval in the file /metabox/MediaAccess.php. eval() is not allowed..
    Line 355: data = eval('(' + (data.indexOf('{') < 0 ? '{' + data + '}' : data) + ')');

    Is it possible to replace the “eval” code by another instruction ? WordPress seems not appreciate eval() function.
    Maybe for the next update 😉

  25. Aaron Vanderzwan

    MediaAccess is great!

    Not a show-stopper, just an FYI. The default editor has to be enabled in order for the MediaAccess ‘Insert’ button to show up (as of 0.1.1). It seems WordPress removes the button completely if the editor is not supported. So… if you are defining your own custom types, just make sure to include ‘editor’ in your ‘support’ arg. If you don’t want the editor, it is currently better to use the WPAlchemy ‘hide_editor’ option (http://www.farinspace.com/wpalchemy-metabox/#display_options).

    Hope this saves some one else some time.

  26. Ed

    Hi Dimas,

    I have the same question as Pietro above, could you post the metabox.php file that goes with the MediaAccess.php code, because it looks great, but I have no idea how to make this functionality work as shown in the video without that code that shows in the editor in the video.

    Thanks!

  27. Jesse

    I’m going to use this for creating a list of slides to use in a slide show on a home page of a wp site. The add / remove option to clone the fieldset is a godsend but I’m wondering how hard it would be to implement some jquery that lets us grab a fieldset instance and drag it up or down – maybe even arrows to click up to move it up in the list of images in order to change the order or fieldset instance number.

    Also wondering if there is a way to limit or set max amount of times something can be cloned. For instance I want the user to be able to add anywhere from 1 to 5 max images for the slideshow but it looks like you can add an infinite amount right now all the way down to none at all.

    Maybe these are feature requests as I’ve seen jquery to allow reordering of fieldset objects but not sure how to use that with the way this class is currently programmed.

  28. Jesse

    Dimas, thanks a bunch! I got them both working exactly like your examples.

    I know this is a work in progress (the media class) but I tried copying the text from the videos for this to my meta box but I get object errors so it’s maybe something to do with the videos being hard to decipher. An example template with the media upload button like your example in the video is what I’m looking for.

  29. alanna

    great work, thanks! works very well.

  30. Jesse

    I didn’t declare a new instance of WPAlchemy_MediaAccess() in my functions file. Works now.

  31. Duong

    Hi Dimas: i can’t find repeating_fields_meta.php and custom_meta.php in https://github.com/farinspace/wpalchemy/blob/dev/wp-content/wpalchemy/ please give me two files. Thanks you!

  32. shawn

    @Dimas

    Any chance you have the time to take a look at my comment from a few months ago?
    http://www.farinspace.com/wordpress-media-uploader-integration/#comment-14671

    I’d still like to see how to get the actual thumbs to show up for images instead of the links. Combine that with the sortable, and my gallery is gonna be so much better than it is now.

    thanks
    *everything else works perfectly, love the class and use it all the time

  33. Ma'moun

    It would be useful if we could also specify a default size for the image.

  34. Ma'moun

    Actually, returning the attachement ID would be so helpful. It’s even far more flexible than getting the image URL. (e.g. it can be used to get different sizes in the front-end template)

  35. Ma'moun

    @Dimas Any chance you can add the ability to get the file attachment IDs to MediaAccess Class?

  36. Fabien

    Thanks for that videos, it helps very much !

    Keep going 😉

  37. kathy

    hi dimas- do you think you can put up a gist or paste the code you are using in your metabox template to get this to work. it is a bit tough to see in the video

  38. kathy

    thanks dimas! i think it’d be much neater to have that folded into alchemy for me, but i’ve patched together something that i use all the time now though. it uploads, stores the url, attachment id and i think it tries to catch alt text too, pulls in a preview, and adds a delete button. the delete button removes the preview image and clears all those hidden fields. maybe you can make use of it if you ever get spare time for this again. you know, b/c i’m sure you have tons of that. 😉

    http://pastebin.com/kigpvmzq

    nb: i have a constant WPALCHEMY which is defined elsewhere as just the URL to my alchemy folder

  39. Melinda

    @kathy
    Thanks for sharing your code! It helped me to pull the image into my metabox that shows the user which image they uploaded, instead of just the image url. What I really want to do is pull the thumbnail of that image into the metabox instead of the full size image. Do you have any idea how to do this?

    Thanks!

  40. kathy

    @melinda – do you mean show the thumbnail as the preview? i’m not sure that is possible unless you select the thumbnail as the size you want to “insert into post”… or i think i’ve hacked it so that the button says “use this image”. the whole thing works by picking up the html that is sent via the “send to editor” function. there is no way to server-side take that image and go get the corresponding thumb.

    all that said, you’ll note in my code that i’ve got a hidden form called image_id. this saves the attachment ID.. which you can then use to produce any version of that image you’d like. say on refresh you can load the thumbnail, or on the front-end you can load the medium size, etc.

  41. Melinda

    @kathy – i did notice the hidden form called image_id and tried adding it to mt metabox template but it doesn’t seem to be saving a value. am i missing something that makes this work? i tried putting get_the_value(‘image_id’)){$mb->the_value(‘image_id’);}?> in my template to see if it would print the attachmen id but nothing is printed.

  42. kathy

    @melinda- the only real “trick” to making it work isn’t really a trick so much as just ensuring that the markup of your mb template matches mine exactly. this is b/c my jquery isn’t universal, but rather, depends heavily on tranversing the DOM as i have set it up. sort of like if i told you to take 2 lefts and then a right you’d end up in a different place if you started from a different place and in a different direction. maybe one day dimas, or myself, or maybe you can come up w/ a better way. that’s just what worked for me at my then-current level of jquery… ie blue belt, but not a ninja. i’ve promoted myself to brown belt now so if i ever have spare time, i’m thinking using IDs and string/preg matching against part of the ID name might work and make it less fragile in this regard.

    sidenote- it only gets IDs for images that you add to the WP database. (ie via uploader) so externally hosted images don’t have IDs. don’t know if you’re running into that or not, but figured i’d mention that is an obvious limitation. i think i have it fall back to using the URL if ID is empty, but i haven’t tested that too robustly.

  43. Brian

    Quick question Dimas,

    Does the user have to have the upload_files capability to implement? The problem I’m having is that I have a custom user role that only sees a custom post type in the backend (does not see posts). I’d like for that user to not see Media either. I’d like to completely isolate them to the post type but still be able to upload and manage their own media.

    If your app does not do this by default, do you have any suggestions of where to look?

  44. arlo

    Not sure if you would consider this a bug or expected behavior, and it is kind of an edge case, but I thought it might help you or someone else to mention this…

    Creating a few custom post types for a plugin. One of the posttypes has:

    'supports' => array( 'title','revisions' )

    I’m not using the editor with this cpt.

    When I use the Media Access meta box with this cpt, clicking the button to launch the media uploader opens it as a new page. I figured out that, because the editor is not invoked, the styles and scripts for the media uploader are not loaded.

    Fixing it was easy — I added to my plugin:

    function my_admin_styles() {
    wp_enqueue_style('thickbox');
    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');
    }
    add_action( 'admin_print_styles', 'my_admin_styles' );

    Now, the admin page has the styles and scripts it needs to launch the media uploader appropriately.

  45. Arlo

    One more fix, also related to disabling the editor for a custom post type: the media uploader doesn’t believe it is actually allowed to insert a file so the insert button is missing.

    This fixed it:
    function allow_file_insertion($vars) {
    $vars['send'] = true; // 'send' as in "Send to Editor"
    return($vars);
    }
    add_filter( 'get_media_item_args', 'allow_file_insertion' );

    Source

    Ought to apply the filter only if the custom post type is what’s being edited, but it was a quick fix for now.

    Thanks for this library. It’s awesome.

  46. Arlo

    Okay, one more comment:

    Is there a method you would recommend for a Javascript function callback once the user picks the file? I wanted to show an icon next to the field once it’s populated. I ultimately had to make a change to the class on line 344:

    wpalchemy_mediafield.val(url);

    Becomes

    wpalchemy_mediafield.val(url).change();

    Then I was able to bind to that change:

    $('input.mediafield').bind('change', function(event) {
    // awesomeness ensues
    }

    It works, but it seems like a hack to me. Is there a better way?

  47. riesurya

    Hi Dimas,
    At first I’d like to say WPAlchemy is amazing. The logic is great 🙂
    Just follow the video above, I try to make save_action for repetitive fields and display separated meta_key and meta_value pair for every fields.

    Unfortunately, the results is empty string on meta_value.

    the scenario :
    custom-spec.php

     '_custom_meta', //make sure it different with other(s) aka spesific
    	'title' => 'My Custom Spec Meta',
    	'template' => get_stylesheet_directory() . '/custom/custom_meta.php',
    	'mode' => WPALCHEMY_MODE_EXTRACT,
    	'prefix' => '_test_',
    	'save_action' => 'my_save_action_function', // defaults to NULL
    	
    ));
    
     function my_save_action_function ( $meta, $post_id )
    {
    	update_post_meta ($post_id, '_test_img_url', $meta['imgurl']);
    	update_post_meta ($post_id, '_test_img_title', $meta['title']);
    } 
    ?>
    

    and on custom-meta.php

    
    
    
    
     
    	<a href="#" rel="nofollow">Remove All</a>
     
    	have_fields_and_multi('docs')): ?&gt;
    	the_group_open(); ?&gt;
     
    		<a href="#" rel="nofollow">Remove</a>
     
    		the_field('imgurl'); ?&gt;
    		setGroupName('img-n'. $mb-&gt;get_the_index())-&gt;setInsertButtonLabel('Insert'); ?&gt;
     
    		
    			getField(array('name' =&gt; $mb-&gt;get_the_name(), 'value' =&gt; $mb-&gt;get_the_value())); ?&gt;
    			getButton(); ?&gt;
    		
     
    		the_field('title'); ?&gt;
    		&lt;label for=&quot;the_name(); ?&gt;"&gt;Title
    		&lt;input type=&quot;text&quot; id=&quot;the_name(); ?&gt;" name="the_name(); ?&gt;" value="the_value(); ?&gt;"/&gt;
     
    	the_group_close(); ?&gt;
    	
     
    	<a href="#" rel="nofollow">Add More Media</a>
    	
    
    

    Thank you before and after. I keep trying how to make it solved, and any solutions and clue is very appreciate.

    hope you can understand my friendly english (my term for “english for non native english” :D)

  48. Armin

    @Dimas Thank you so much for this plugin! It is so exactly what i need and i found it through a blog post on smashing magazine (someone commented about your plugin) that was posted on the exact day i need it (today). Love those coincidences.

    So i followed the instructions to set up WPAlchemy and get it running and it works fine, but when i try to implement the example above I always get the following error:

    Fatal error: Call to a member function setGroupName() on a non-object in /home/seltzde1/public_html/athena/wp-content/themes/yoko/metaboxes/custom-meta.php on line 5

    I have checked many times over and am copy and pasting everything from your examples into the right files. I get the same error for the 1st and 2nd example. Thats where i am stuck right now. Im sure its just something small, but everything seems exactly like you have it. Help is much appreciated! Thanks.

  49. Armin

    @Dimas

    Ok i should have watched the video straight away. In the video you mention the importance of this part:

    $wpalchemy_media_access = NEW WPAlchemy_MediaAccess();

    But this is not found in the code boxes you give above, which I used to copy and paste from. I now put it at the end of setup.php and voila it works. Maybe you should include it there, so it doesnt happen to others who are as impatient as me and dont watch the video first 🙂

    So now for the real fun part.. Im sure ill have a few more questions soon.

  50. Gonzalo Sanchez

    Hello Dimas.
    Great work man!
    Thank you very much. Really.

    I have a problem. Is it possible to nest two the_group_open()?
    I need to create a repeatable set of fields which in turn contain another set of repeatable media upload fields. What do you think?

    Thanks in advance.
    You’ve launched WordPress to the next level!
    ( I have you in my donations Christmas list 🙂

  51. Gonzalo Sanchez

    ok, try another solution.

    For example, a “title” field accompanied by a fixed number of fields for images, and the entire block is repeatable.
    Not the most elegant solution but it would work. While we await the release of the next version of WPAlchemy! 🙂

    Another question friend. What is the way to store the attachment_id instead of the image path? Or both 😉
    I ask the question directly instead of filling the post with the adventures I’ve tried to get the ettacment_id (unsuccessfully).

    Dameian said something about this in one comment (April 12, 2011) but I can not find the solution that way.

  52. OVX Solutions

    thanks for sharing,its much easier to add on my wp site.thanks

  53. Nick

    Hey Dimas, thanks for all of your work!

    I’d suggest including this into boxes above (also had the issue but found solution in comments):


    // the name of the instantiated class object
    global $wpalchemy_media_access;

    Thanks,
    Nick

  54. Nick

    Sorry, meant this one:


    $wpalchemy_media_access = NEW WPAlchemy_MediaAccess();

  55. Paco

    Hi Dimas, I did everything you recommend above and what I have are just Remove and Remove All buttons. What did I do wrong ? I am using the last version of WPAlchemy…

    Thanks for your help 🙂

  56. Matthew

    Hi,

    great work so far! I tried the “Repeating Fields Functionality” but for some reason the mentioned Version 1.4.5 of the MetaBox.php is missing at GitHub. Is there a chance to receive this one?

    Best Regards
    Matthew

  57. Horia Ancas

    Ciao Dimas,
    I am trying to use the media uploader with PDF files. The problem I have is the url to the PDF is not placed into the text input. It is working perfectly with image files, but with PDF is a no go.
    Can you give me some suggestions ? I am looking in the source, but I am not much of a programmer.

    Thanks a lot.

  58. David

    Is it normal that when I insert my picture using the Media Upload box, it get inserted into the normal wordpress editor box? I can’t get it to work…

  59. Scott Lee

    I’d like to make the images links (via the Link URL field in the uploader). Is there a way to do this using the MediaAccess helper you’ve created?

  60. frances

    Hallo Dimas,

    I’ve just upgraded one of my sites to WP3.3, which uses MediaAccess. It seems it works fine, and is much the same as before (with the caveat of this being a specific situation and only one test).

    Tested with 0.2.1.

    Frances

  61. Pierre

    Hello there,

    Something weird with the media uploader: I use the “wp_get_attachment_image_src” function to display my images, which works correctly for brand new uploaded (from the computer) images, but fails in the case of yet existing images picked in the library: the URL is saved as meta date, but there is no more attachment with the post…
    Am I doing something wrong?
    Thanks!

  62. Satrya

    Hi there,

    I got this error message
    Fatal error: Call to a member function setGroupName() on a non-object in mypath\custom-meta.php on line 5

    Can you explain this ?

    Thanks !

  63. cezarion

    Hello,

    I’had the same problem.
    in yourtheme/metabox/setup.php

    After:

    function my_metabox_styles()
    {
        if ( is_admin() )
        {
            wp_enqueue_style( 'wpalchemy-metabox', get_stylesheet_directory_uri() . '/metaboxes/meta.css' );
        }
    }
    

    add this line:

    $wpalchemy_media_access = new WPAlchemy_MediaAccess();
    
  64. Aris Blevins

    Hi Dimas,

    Amazing work on with WP Alchemy, I am really amazed at how clean and flexible this code is. Adding the Media Access functions is an exponential leap as well. Thanks!

    I am having a small issue, which may not be easily fixed. I have a CPT that I would like to attach two galleries to. I was originally going to have one gallery be created using the standard Attachment method, and then have meta fields pointing to the other images. With Media Access I was hoping I could include the second gallery as images uploaded via this meta-box – of course those images are just added to rest of the post gallery.

    Probably no way around this eh? Short of excluding those images from the gallery?

  65. Paul

    Hi

    where would I set the upload path for it to be different from the regular media upload button at the top of the post edit screen?
    thanks

  66. Paul

    I know that. What I mean is I want uploads managed by WP Alchemy to go to a different folder.
    I know there’s an ‘uploads_dir” filter hook for example. Maybe I can conditionally change the uploads folder when uploading with the wp alchemy metaboxes?

  67. Anders Kitson

    How do I go about outputting this in a template. specifically grabbing the imgurl from a certain page and displaying it on such. I have tried numerous things to no avail.

  68. Ian

    I’m using Netbeans, too…..

  69. Bebopweb

    Hello,
    I currently use the WordPress Media upload but I would like to add a sticker next to the delete button. Is this possible? If so, can you help me.
    Thank you in advance

  70. alrobeler

    Hi!how to display the above code
    in my theme?

  71. stephan

    Hi Dimas,

    Is there a way to prevent images from being added to the gallery?

    Thanks for all the hard work!

  72. Clay

    great library here but i faced a problem with the latest wp and i’m wondering whether this is an issue. Following all the instruction here, everything looks good until i start uploading images the insert button still said ‘Insert into Post’ instead of the one i customized it which cause it to keep inserting into the editor, any idea? 🙁

  73. Alan

    Could you please provide an example of how to save the value of ‘imgurl’ when the post is publsihed and then put it back in the field when the post is edited.

    Thanks

  74. Rafael Vinícius

    Hi Dimas

    Is there a way to prevent images from being added to the gallery?

  75. johnnya23

    Is it possible to retrieve the attachment id instead of the url and at the same time have some kind of useful feedback (not just the id#) to be shown on the dashboard?
    Thanks for a great plugin,
    John

  76. tony

    Hi Dimas,

    Good Day, I copied the same code for the media repeater however i kept getting error Fatal error: Call to a member function setGroupName() on a non-object in C:\wamp\www\site\wp-content\themes\windsorblinds\backend\functions\metaboxes\product-meta.php on line 38

    version 1.5.2

    Thanks,

    Tony

  77. slona

    How to echo the fields into my theme? Using
    foreach ($meta['docs'] as $link)
    I get “Invalid argument supplied for foreach()”

  78. slona

    Ooops, my falut, I messed up variable names. It’s working now. Echo the fields using:

    global $custom_mb;
    $meta = $custom_mb->the_meta();

    foreach ($meta['docs'] as $link)
    {
    echo $link['imgurl'];
    }