WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Tutorials» How to Add Additional Fields to the WordPress Media Uploader

How to Add Additional Fields to the WordPress Media Uploader

Last updated on February 8th, 2012 by Editorial Staff
23 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
How to Add Additional Fields to the WordPress Media Uploader

While working on a project where we created a very cool gallery powered totally by WordPress attachments and a custom post type, we found a need to add additional fields to the WordPress media uploader. These additional fields allowed us to give each photographer credit by adding photographer name, and their URL on each image page. WordPress stores images as posts in the attachment post type, so adding meta data is just like adding custom fields. Because the WordPress attachments does not have a custom fields UI, we have to add a custom fields to the media uploader in order to collect the meta data. In this article, we will show you how to add additional fields to the WordPress Media Uploader.

We will be using the following filters to make the change: attachment_fields_to_edit and attachment_fields_to_save

For a project like this, we highly recommend that you create a site-specific plugin and add the following code. However, you can still add the codes in your theme’s functions.php file to make it work.

/**
 * Add Photographer Name and URL fields to media uploader
 *
 * @param $form_fields array, fields to include in attachment form
 * @param $post object, attachment record in database
 * @return $form_fields, modified form fields
 */
 
function be_attachment_field_credit( $form_fields, $post ) {
	$form_fields['be-photographer-name'] = array(
		'label' => 'Photographer Name',
		'input' => 'text',
		'value' => get_post_meta( $post->ID, 'be_photographer_name', true ),
		'helps' => 'If provided, photo credit will be displayed',
	);

	$form_fields['be-photographer-url'] = array(
		'label' => 'Photographer URL',
		'input' => 'text',
		'value' => get_post_meta( $post->ID, 'be_photographer_url', true ),
		'helps' => 'Add Photographer URL',
	);

	return $form_fields;
}

add_filter( 'attachment_fields_to_edit', 'be_attachment_field_credit', 10, 2 );

/**
 * Save values of Photographer Name and URL in media uploader
 *
 * @param $post array, the post data for database
 * @param $attachment array, attachment fields from $_POST form
 * @return $post array, modified post data
 */

function be_attachment_field_credit_save( $post, $attachment ) {
	if( isset( $attachment['be-photographer-name'] ) )
		update_post_meta( $post['ID'], 'be_photographer_name', $attachment['be-photographer-name'] );

	if( isset( $attachment['be-photographer-url'] ) )
update_post_meta( $post['ID'], 'be_photographer_url', esc_url( $attachment['be-photographer-url'] ) );

	return $post;
}

add_filter( 'attachment_fields_to_save', 'be_attachment_field_credit_save', 10, 2 );
?>

The code above will add two text fields to the Media Uploader called Photographer Name and Photographer URL. You can see that in the screenshot below:

Additional Fields in the Media Uploader

Explanation of the code: In the first function, we are simply using an array to specify the field’s label, input type, value, and help text. The second function is checking to see if a value has been set for those fields. IF the value is set, then the post metadata is updated.

If you want to display the fields in your attachments template, then simply paste the following codes inside the loop:

echo get_post_meta($post->ID, 'be_photographer_url', true);

If you want to display the fields for your featured image in your archive template or any other template, then simply use:

echo get_post_meta(get_post_thumbnail_id(), 'be_photographer_url', true);

We hope that you enjoyed this article. For those who don’t know how to create an attachment’s template, don’t worry. In the next article, we will cover how to create an attachment’s template in WordPress.

Hat Tip to Bill Erickson for showing us how to do this.

23 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • How to Fix the Error Establishing a Database Connection in WordPress

    How to Fix the Error Establishing a Database Connection in WordPress

  • Revealed: Why Building an Email List is so Important Today (6 Reasons)

    Revealed: Why Building an Email List is so Important Today (6 Reasons)

  • How to Start Your Own Podcast (Step by Step)

    How to Start Your Own Podcast (Step by Step)

  • How to Properly Move Your Blog from WordPress.com to WordPress.org

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

32 Comments

Leave a Reply
  1. Viktor says:
    Sep 17, 2018 at 3:42 am

    Nice tutorial, but is there a way how to add these credits when inserting the image into the post?

    thanks

    Reply
  2. Nevena says:
    Sep 10, 2016 at 3:59 am

    Hi,

    I need to link my featured image of the custom post to external link. I tried this code, but when I click on image, it doesn’t go to link. What am I doing wrong?

    Reply
  3. fynn says:
    Apr 6, 2016 at 8:51 am

    this does not seem to work anymore with wp 4.2.2
    its not saving the entry

    Reply
  4. Nuno says:
    Mar 4, 2016 at 6:35 am

    Hi,

    Can we have a custom field on the image details pop-up ?

    Thank you

    Reply
  5. Rihan says:
    Feb 18, 2016 at 2:11 am

    Thank you for the great post..

    and can you help me how to add check box ( not text field )?? i try to change
    $form_fields[‘be-photographer-name’] = array(
    ‘label’ => ‘Photographer Name’,
    ‘input’ => ‘checkbox’,
    ‘value’ => get_post_meta( $post->ID, ‘be_photographer_name’, true ),
    ‘helps’ => ‘If provided, photo credit will be displayed’,
    );

    and its not working

    Reply
  6. Ellis says:
    Apr 16, 2015 at 6:52 am

    This is great and just what I was looking for. However, I’d love to have those extra fields (photographer’s name, url) available in the “Image Details” window within the post Editor as well, can this be done?

    Reply
    • Alex says:
      Nov 9, 2015 at 10:57 am

      I’d like to know this too :)

      Reply
      • J. Todd Baker says:
        Aug 21, 2016 at 9:27 pm

        Alex, did you ever get a solution to this? I am looking to do this as well. Thanks!

        Reply
  7. Andreas Morgta says:
    Feb 10, 2015 at 1:26 am

    great tutorial, thanks alot for writing it.

    Unfortunately it isn’t working with the great plugin “Enhanced Media Library”:

    The bulk editor just loads and loads… :(

    Any idea how to fix that?

    Reply
    • Jess Tura says:
      Feb 23, 2015 at 12:29 pm

      check your ending pair of the php tags.

      maybe do not copy line 48 at the above code as the plugin code from another tutorial has it already.

      Reply
  8. test says:
    May 28, 2014 at 7:31 am

    Hi,

    What code do I have to insert to make this show on an image within a post (not a featured image)?

    Thanks.

    Reply
  9. Domingos says:
    Jan 21, 2014 at 4:15 am

    The fields are being displayed in the media upload, but the output is not showing up in any of my template files. I’ve added this code to my content.php but nothing is showing up:
    ID, ‘be_photographer_url’, true);?>

    Also tried with:

    I’ve also test it on the twentytwelve theme and there it’s also not showing up.

    Reply
  10. James Murray says:
    Oct 2, 2013 at 10:33 am

    Thanks for the tutorial. I’ve used it on my site and the custom fields work great – I just have a problem in that it screws with the modal menu. This means that when my users go to ‘Add Media’ in the post panel, they won’t see anything in the media library, won’t be able to set the default image etc. I’ve tried setting $form_fields[“custom_field”][“show_in_modal”] = false; but that doesn’t make a difference. It seems as soon as I mess with attachment_fields_to_edit I get this error.

    Reply
    • James Murray says:
      Oct 10, 2013 at 10:15 am

      Update on this – I was calling a jquery datepicker for one of my extra fields and this didn’t agree with the modal menu. Got around it by only calling the javascript when the url ends in action=edit – hope that helps if anyone else comes across this rare problem!

      Reply
  11. Linus says:
    Aug 30, 2013 at 10:31 am

    Hello!

    Really nice tutorial!
    In this case i’m using this for gallery purposes, where the user can add extra info. This info will be captured in the jQuery prettyPhoto later. The user should be able to use the same image in multiple albums (on different pages that is) but with different captions. So, i guess i have to make some logic that saves the values as a json string, where the first value is the page id number (not the attachment id number). How can i get that page (or post for that matter) id number, inside of this function?

    Reply
  12. Patrik Illy says:
    Apr 17, 2013 at 10:38 am

    Hi,
    thanks for article, is it useful. I have one question. I have set categories for media and i need to use filter by this categories in media uploader, ideally next to filter by media type… Is there any solution how to add select with used categories on this place?

    Thanks for reply

    Reply
    • Editorial Staff says:
      Apr 18, 2013 at 8:27 am

      See if something like this would help you:

      http://wordpress.stackexchange.com/questions/29858/adding-category-tag-taxonomy-support-to-images-media

      Reply
      • Patrik Illy says:
        Apr 18, 2013 at 9:13 am

        Thank for reply. I looked on this post, but its all about adding new column on media library. I need add dropdown form item with used categories on lightbox media uploader…

        Reply
  13. Baylock says:
    Feb 26, 2013 at 8:17 pm

    Hi,

    Thanks for this neat trick.
    One question though: How would I put these news fields above some of the native ones?
    Let’s say I would like to add a field just after the “Caption” field…
    I tried to mess with the value in the “add_filter” but it doesn’t seem to change anything.

    Thanks for your help!

    Reply
    • Editorial Staff says:
      Feb 27, 2013 at 6:10 am

      Modify the priority numbers from 10 to 5.

      Reply
      • Baylock says:
        Feb 27, 2013 at 7:25 am

        As I said, that’s what I did with no success.

        In the meantime, I found a workaround:

        I unset the other fields like this:

        $image_size_field = $form_fields[‘image-size’];
        unset($form_fields[‘image-size’]);

        I declare the new fields by using your script and THEN I set the unset fields when needed like this:

        $form_fields[‘image-size’] = $image_size_field;

        This way, the “size” field (for instance), will appear after the two new fields.
        It did the trick.

        Thank you.

        Reply
  14. Donna Fontenot says:
    Dec 29, 2012 at 11:16 pm

    Good stuff, thanks!

    Now, here’s an idea for another post. :) I’m a bit aggravated with the latest media uploader. When looking at images that we’ve uploaded within the post editor (as opposed to looking at images within the media admin section), the window no longer shows the file url of the image there. (We used to copy/paste that url into a custom field after uploading an image into a post). Now, we have to get out of the post edit screen (or open a new tab) and go to the media admin section, find the image, and grab the file url from that window, come back to the post, and paste it into a custom field. So, how about writing a post on how to display that file url in the media window WITHIN the post editing screen, like it used to have? I know I’d appreciate that post! :)

    Reply
  15. Sacha says:
    Sep 24, 2012 at 10:07 am

    Excellent code!

    But what if I need to display the gallery with the [gallery] shortcode, how can i tell WP to add my new custom fields?
    Any ideas?

    Reply
  16. smattiza says:
    Apr 17, 2012 at 12:12 pm

    i apologize if dumb question but…i have added to functions.php but do not know where to place the echo code in order to display the credit under photos – esp. on home, category and single posts.  Would someone please help with any instruction.  Thank you very much.

    Reply
    • wpbeginner says:
      Apr 19, 2012 at 6:24 am

       @smattiza You can display the code in your single.php file, archive.php, category.php or any of those files. It needs to be displayed inside the loop.

      Reply
  17. Editorial Staff says:
    Mar 6, 2012 at 12:11 pm

    Not sure why you are getting the error because we literally copy and pasted the code from our plugin file.

    Reply
  18. EB says:
    Mar 4, 2012 at 10:35 pm

    I tried this — my first attempt at a plugin — and it wouldn’t activate. I got this fatal error. (Just FYI, my line 15 is = to your line 10): Parse error: syntax error, unexpected T_VARIABLE in /home/blackmom/public_html/wp-content/plugins/credit-and-courtesy-by-eb/photocreditplugin.php on line 15

    Reply
    • wpbeginner says:
      Apr 19, 2012 at 6:23 am

      That line has nothing to do with it. It seems that the error is happening before that.

      Reply
  19. markus says:
    Feb 24, 2012 at 4:08 am

    Thanks for your code! Any idé how i can add the tinymce editor to one of this inputs? 
     

    Reply
  20. wpbeginner says:
    Feb 8, 2012 at 8:09 am

    Hey Bill,

    We modified and added do not add http:// because most users who enter the data always enter the URLs without it. So when displaying it in the single attachment file, we simply added http:// before adding this tag. However, you are right that adding the esc_url would make it much easier. Thanks. Updated the post.

    Reply
    • wpbeginner says:
      Feb 8, 2012 at 8:25 am

      Just remembered that another reason was that we wanted to display the URL itself without the http:// as text.

      Reply
  21. Bill Erickson says:
    Feb 7, 2012 at 11:49 am

    For the URL field, instead of telling the user not to include the http://, change your be_attachment_field_credit_save() function to this:

    if( isset( $attachment[‘be-photographer-url’] ) )

    update_post_meta( $post[‘ID’], ‘be_photographer_url’, esc_url( $attachment[‘be-photographer-url’] ) );

    esc_url will ensure it is a properly formatted URL.

    Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
WP Mail SMTP logo
WP Mail SMTP
Fix WordPress email delivery issues. #1 SMTP plugin. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2020 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2020)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2020)
    • SiteGround Reviews from 4196 Users & Our Experts (2020)
    • Bluehost Review from Real Users + Performance Stats (2020)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2020 – Step by Step Guide
Deals & Coupons (view all)
ThemeIsle Coupon
Get 10% off ThemeIsle themes when you use this coupon.
All in One SEO
All in One SEO Coupon
Get 50% off All in One SEO, the #1 WordPress SEO plugin. Great for beginners and advanced users.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).
Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress CDN by MaxCDN | WordPress Security by Sucuri.