WordPress has very beautiful and useful media uploader. It is used to attach images to posts and featured images to posts.

Sometimes need may arise that we want to add some extra or we can say custom field to media uploader of wordpress.

For Example: We want to show only those images in slider which have values to the custom field of media uploader.

myphoto (3)

So, Today we are going to see how can we add custom field to wordpress media uploader.

This task is very simple and can be accomplished in simple two steps.

Step 1: Add custom field to media uploader.

function st_custom_field( $form_fields, $post ){

 $form_fields["st-img-link"] = array(
   "label" => __("Custom Field"),
   "input" => "text",
   "value" => get_post_meta($post->ID, "_st_img_link",true),
   "helps" => "Descriptive text about purpose of adding custom field"
   );

  return $form_fields;
}
add_filter("attachment_fields_to_edit", "st_custom_field", null, 2);

And here we go we have added the custom field to media uploader. Here we have given label , input type, value for input and help text for custom field.

Now, come to the second step.

Step 2: Save value of custom field.


function st_save_custom_field( $post, $attachment ){

  if( isset($attachment['st-img-link']) ){
   update_post_meta($post['ID'], '_st_img_link', $attachment['st-img-link']);
  }
  return $post;
}
add_filter("attachment_fields_to_save","st_save_custom_field",null,2);

And that’s it here we all done.

In step 2 we are saving the custom field value as ‘_st_img_link’ which  we are retrieving in step 1.

Note: In step 1 $post is object whereas in step 2 it is an array.

In this way we can add custom field to wordpress media uploader

Add custom field to wordpress media uploader

3 thoughts on “Add custom field to wordpress media uploader

  • February 18, 2013 at 12:51 pm
    Permalink

    Nice tutorial dude.
    You saved my lot of time 🙂

    Reply
  • July 16, 2013 at 10:00 am
    Permalink

    Hi!
    How can I do to print this news metadata-fileds on website?

    Thank you!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *