Blog

Sharing WordPress tips and tricks as I find them

Adding fields to the Media Gallery

This post has been marked as old. The code might no longer work. Comments have been disabled as this is no longer maintained.

In WordPress 3.5, the media gallery was completely rebuilt, and now the method described below doesn't work. Here's a tutorial that might help.

Images in WordPress can have as much metadata (data about the image) as you want. WordPress stores images as posts in the “attachment” post type, so all the standard WordPress functions you’re used to using with posts also work with images. For example, captions are stored as excerpts.

If you want to collect additional information on a post you typically use a metabox. For images, you can add your custom fields directly to the media uploader.

There’s two filters we’ll use: attachment_fields_to_edit and attachment_fields_to_save.

I’m going to provide two examples that I use often: adding a “Photo credit” section, and adding an “Include in Rotator” selection.

Adding Photo Credit

You’ll often need to provide attribution to the source of images you use on your website. Rather than sticking it at the top or bottom of the post, we can add that information as photo metadata and then include it in the theme.

I’m going to add two text fields, Photographer Name and Photographer URL.

In the first function we used a simple array to specify the field’s Label, input type, value, and help text. In the second function, we check to see if a value has been set for those fields, and if so we update the post metadata.

To access this information in our theme, we simply have to get the post meta for the thumbnail. Assuming we want it for the featured image, we’d do something like this: get_post_meta( get_post_thumbnail_id(), 'be_photographer_name', true );

Include in Rotator

Adding text fields is rather easy. What if you want something more custom? If you use the ‘html’ input type, you can output whatever HTML you’d like.

I love using the built-in Gallery feature in WordPress for managing image rotators on specific posts or pages. The problem is that all images are included in the gallery. So I add an “Include in Rotator” option when editing the image, and then I can query for all attached images that were marked “Yes”.

For more examples of creating html inputs for the media gallery, look in /wp-admin/includes/media.php.

Then when I want to get all the attached images that are going in the rotator, I run something like this:

70 Comments

  1. Awesome tip, especially useful when it comes to the photo credits/links!

  2. Nice one Bill. Thanks:)

  3. Wow. Really awesome stuff and not least a very usable tip. Thanks a lot.
    Great site. Bookmarked!

  4. Great tip!! Thanks Bill, I appreciate you posting this, really helped me out.
    - John

  5. Hey Bill! Thank you for the tip. I was trying to implement your code and found a typo which caused an error. You missed the letter ‘S’ in add_filter( ‘attachment_field_to_save’, ‘be_attachment_field_credit_save’, 10, 2 ). The name of the filter to hook should be ‘attachment_fields_to_save’.

  6. Thanks for the tip Bill. This will save a lot of time.

    BTW I bought Driskill last night. Very nice. I planned to make something similar for one of my sites but buying yours was much ea

  7. This may be a duplicate. My iPad is acting a little wonky.

    Thanks for the tips here. They will save a lot of time and hassle.

    Also, thought I mention that I bought Driskill last night. Very nice and just what I needed. I was planning to make something similar for one of my sites. Buying your theme was much easier and faster. The responsive design was icing on the cake.

    Bob

  8. This is awesome! Is there a way to limit the fields to a specific mime type? For example, add fields that have a mime type of ‘video’ and not to ‘images’?

    • Bill Erickson says:

      That’s a great question. I’ve never tried that. I recommend looking at the $post object to see if it has the mime type in it, or you can do $mime = get_post_mime_type( $post->ID );

      More info: http://codex.wordpress.org/Function_Reference/get_post_mime_type

      • Sweet, thanks! Actually, I just figured it out of I posted. In this case it was for audio, in which I though ‘audio’ would work, but had to use ‘audio/mpeg’ when get post mime type.

        $post_mime_type = ( 'audio/mpeg' == get_post_mime_type( $post ) ) ? 1 : 0;

        Then I just did an simple if statement in be_attachment_field_credit().

        if( 1 == $post_mime_type ) {
        $form_fields[...] = array(...);
        }

        It seems to then show the fields on audio/mpeg type files, and not an images/video or other mime types.

        Great post!

  9. Thanks Bill Erickson this helped me to solve my problem, as i want to display my customized fields and make some validations on the media.php file so that it could validate the media form………

    i made the changes in _save method it resolved…
    thanks alot again

  10. I love you! More seriously, this is EXACTLY what I had been looking for. Thank you so much! Now, if I could bother you for how to make the first example multilingual ? (adding photo credit, how to make it so that label and helps can be automatically translated within the plugin I am creating? )

  11. is it possible to use these fields in a meta_query?

    • Bill Erickson says:

      Yes it is. The last code example in the post shows it being used in a meta_query.

      • thanks Bill, what I mean is can I do something like:
        “fetch all posts that have this value for the attachment custom field”
        on a custom post archive for example.
        it’s getting late here…sorry

        • Bill Erickson says:

          Hmm, I don’t think that’s possible with a simple query. Here’s how I’d try doing it:
          - Query for all attachment posts that have the specific custom field you want (last example in the post).
          - Loop through the posts, adding the post_parent’s to an array if not already there
          - Do a query for those posts

          Something like this (completely untested): https://gist.github.com/1403244

          • thanks for taking the time to post that code Bill. That may work!
            Would be cool though to be able to query directly the attachments meta values from the parent post.

          • Bill Erickson says:

            It would be, but they are stored as separate posts. Attachments are posts, as are the main posts. The metadata of the attachment doesn’t contain any link to the main post. If you’re good with SQL you might be able to write a direct SQL query that can accomplish this, but I much prefer using WP Queries.

  12. Absolutely brilliant stuff here, thanks so much.
    Been looking for the ability to add form fields like this right in functions.php without having to edit the core.

    Followup question…any idea how I might go about adding a button to the same form area?

    I’d like to add some buttons that wouldn’t even need values to be saved…they would instead receive functionality via jQuery to perform tasks.

  13. Gregory Schultz says:

    This is exactly what I’ve been looking for and thanks for putting this on the Internet. However, I’m not an expert on coding but I do know how to do basic coding and I’m stumped on how to display the custom field on my site. I added the ‘photo credit’ to my functions.php and I was able to add data to my images. I just need help on displaying the custom field on my site.

    I’m using this to display image attachments on my site:
    ‘id); $args = array( ‘post_type’ => ‘attachment’,’post_status’ => null,’post_parent’ => $post->ID,’include’ => $thumb_id);
    $thumb_images = get_posts($args);
    foreach ($thumb_images as $thumb_image) {
    if($thumb_image->tqmcf_disable) echo ”,’Image: ‘ . $thumb_image->tqmcf_disable . ”;
    }
    ?>’

    Thank you for putting this online and I appreciate any help in helping me,
    Gregory S.

    • Bill Erickson says:

      It’s stored as postmeta, so to get the photographer name inside your loop, use something like this:

      echo get_post_meta( $thumb_image->ID, 'be_photographer_name', true );

      You might also look into using WP_Query for doing your queries rather than get_posts

      • Gregory Schultz says:

        Huzzah! I finally got it to work.

        One final question. How do you only display the custom field if data has been entered? I’ve tried doing an ‘if’ statement and it didn’t work. This is what I have so far:

        ‘ get_the_ID(), ‘post_type’ => ‘attachment’, ‘post_mime_type’ =>’image’) );
        foreach ( $attachments as $attachment_id => $attachment ) {
        if (get_post_meta($attachment_id, ‘photo_credits’, true)) echo ”,’Image: ‘ . get_post_meta($attachment_id, ‘photo_credits’, true) . ”;
        } ?>’

        I appreciate the help,
        Gregory S.

  14. Thanks for this great tutorial. I have a small problem. I’m using a plugin called simple-portfolio. I want to add some custom fields when I create a project in this plugin I can add images. I want to add some custom fields to these images. I made a functions.php file in my theme folder with your functions from this post. The problem is the media uploader doesn’t save the fields. When I go to the Media plugin from WordPress and edit an image I added in the plugin it DOES save these fields. Any simple solution or should I contact the developer of the plugin?

    • Bill Erickson says:

      I’ve never used that plugin before so I can’t comment on why it isn’t working. It’s best to contact the developer of the plugin

  15. Additional bit of code to wrap around the add fields section, so these fields only apply to images:

    // for audio files
    if( substr($post->post_mime_type, 0, 5) == ‘image’ ){
    // Create data fields for images below.
    }

    Just tidies up the code and confusing the user with unnecessary fields when dealing with other media types.

    One observation if you view the media library you will see that the URL uploader help text doesn’t have a br tag leaving additional fields below it out of alignment. Going to create a bug report about it, just don’t know how to fix it in the meantime.

    Thanks for the code, it’s exactly what I was looking for a models ‘folio site.

    • Fixed the broken layout, it comes down to the CSS class: .media-item .describe th

      It’s set to 140px which is too narrow for long label names resulting in a broken layout, over-riding the class with a width of 180px resolves the problem.on the media page, seems the iframe isn’t affected at least with the label names I’m using,

  16. weston deboer says:

    Worked great! I have been looking for something like this for ages.

  17. That’s a cool tip. The way WP handles fields as an array is cool. I haven’t known about this before. Thank you!

  18. Cor van Noorloos says:

    Hello Bill,

    As I’m currently using Genesis for only a small set of projects of mine, I’m not entirely sure if it would be appropriate to ask this here.

    Would it be possible to also extend the WP default settings using this tutorial?

    Lets say I’d like to hide the media ‘Attachment Post URL’, and make the ‘None’ and ‘File URL’ button into a checkbox/radio button (which reads in my case, modal window true/false).

    A small mockup: http://d.pr/JpH1 and https://gist.github.com/1817917

  19. How can I save an array of checkboxes? I’m trying to tag WordPress Users in individual post-attachments.
    https://gist.github.com/1957528

  20. This is quite awesome. One thing I noticed though is the data wasn’t being saved automatically when images were uploaded (and I needed images to default to yes and display), so what I did instead was pull the meta using:

    https://gist.github.com/2396076

    That way I could just test using:

    if($be_rotator_include !=’1′) { //do something awesome }

    Anyway. Awesome stuff. Thanks!

    • Bill Erickson says:

      Another approach is to limit your query results to those matching the meta query: http://www.billerickson.net/code/get-attached-images/

      • The reason that didn’t work for me is because the meta data doesn’t get saved until the user goes into the gallery and saves the image – when I just upload an image to a post $be_rotator_include returns NULL until actually going to the gallery and clicking save changes. I needed all images to show up automatically unless the value was set to “no”.

        I’ve tried using meta_compare and relations and nothing…any ideas? thanks!

        • Bill Erickson says:

          You could hook onto the save_post hook, check the post meta, and if it’s empty save it with whatever you’d want. Or you can do it your way.

          I usually take the opposite approach where I only want images marked “Yes” showing up. If they upload an image, I want them to actually check “include in rotator” before it shows up.

          • Thanks for the insanely fast reply. Yes I ended up just creating a small update_post_meta function to loop through any images already on the site then hook into save_post.

            Didn’t know if there was a better/quicker way using the meta_query to check if the attachment had a meta value or not, but I guess you can’t check it this way…

  21. Bill, I hate to post what is likely a very easy/dumb question but I am new to WP and trying to get a credit to display under images in posts. I added your code to the functions.php but do not know where to add the code (echo) to display the credit for images on single posts and cat indexes, etc. I would greatly appreciate any help. thanks!

    • Bill Erickson says:

      Is this for the featured image, or for normal images inserted in the post? I don’t this technique can be used for the latter, but to include it on the featured image look in your template file (probably single.php) for where the featured image is being inserted. You’ll see the_post_thumbnail() or get_the_post_thumbnail(). Place your get_post_meta() function below this.

  22. I’m trying to figure out a way to get credits to automatically display on images inserted into the content body… I’m a bit stumped. I looked at a pair of plugins that purport to do this, but both seem to inject the credits into shortcode at the time the photo is inserted…
    For reference:
    http://wordpress.org/extend/plugins/media-credit/ <- wraps image in shortcode on insertion.
    http://wordpress.org/extend/plugins/image-credit/ <- never got it even slightly working

    This all leads me to believe there isn't a good way to do this at the time the post is rendered, and just to make sure I'm not totally missing something, I'm thinking there is no processing that happens inside the_content, hence no hooks… and the only available filter would be on the_content which would make for an ugly task if one tried to find the img tags, then the credits associated with them based on ??? and then injecting html around them…

    • Bill Erickson says:

      Correct, there’s no easy way to apply this to images inserted in the post. You’d need to use the_content filter to run a regular expression to find all images.

      • Thanks Bill… getting off topic, but this got me thinking… wouldn’t an “WP image object” be kind of cool? Something that one could insert into the post body but that one would continue to have full programatic control over similar to featured images. It could be prototyped with shortcodes providing the hook in point I suppose, but I’m thinking of it as a core feature… Just a day dream… that level of core hackery is at the limits of my imagination, and well beyond my skills, just and interesting idea for now.

  23. Thanks for the great article. This is exactly what I was looking for.

    One question – is it possible to have the data from the extra fields inserted into the editor when one clicks on Insert Into Post? If so, how does one do this?

    Thanks in advance for any help you can offer.

  24. Very nice tip! Thanks for sharing.
    Just a question: is there a way to only display the custom field only when a certain page template is selected ?

    Thanks

  25. Great tutorial. I was wondering how I could use the hidden custom field feature to do this.

    I was expecting to just replace “be_photographer_url” with “_be_photographer_url” but then it actually doesn’t work. Is their a way to use this with those hidden fields?

    In case you don’t know what I mean by hidden fields, it’s the ability to save to a custom meta field, but then not have that custom field appear in the “Custom Field” drop down list.

    Thanks,
    Drew

    • Bill Erickson says:

      Since these fields are for media, not posts, there isn’t a Custom Fields box that you need to hide the fields from. If you want to add a field without having an input, just don’t add the input field.

  26. Nice one! Great post and good topic.

    (Sorry, I usually don’t leave short random comments, but the fact that I am says how much I like this post!)

  27. This is pretty darn awesome and works perfectly. Thank you! Any thoughts on how to go about putting in functionality to bulk edit these fields in the media uploader or in the media library?

  28. Bill, could this code be used to add tags to media? I haven’t had much luck with the two plugins that are available. Thanks.

    • Bill Erickson says:

      It can be used to add a text field to the media screen (post meta on the attachment), but I’m not sure how it work work for a taxonomy.

  29. Hi Bill,

    Works like a charm! Thank you for sharing it.
    Just one question though: I want the images to be included by default in the rotator so I’ve put $selected = ’1′;. and I’m using this code for blog posts. The issue is that if I have previously uploaded images in older posts before adding the code for the “Include in Rotator” option the “be_rotator_include” field seems to be set to null which results in the images not being included in the rotator. The only solution I’ve found so far is to resave the changes for the images. Is there a way to query for the images which “be_rotator_include” field is set to either 1 or null?

    Thank you.

  30. hi Bill,
    Your code has worked fine for me in the past, but seems broken in wordpress 3.5. I am trying it out in my local development environment so dont have a website example to give you, but this is understandable given that 3.5 has changed things regarding attachments – is there code that works with 3.5 yet? I have googled everywhere but no one seems to have any answers yet. Cheers.

    • Bill Erickson says:

      Correct, this tutorial does not work with the new media uploader. I’ve marked this post as old since the code doesn’t work, and included a link to a tutorial describing how to customize the 3.5 editor.