Adding attachment meta fields in WordPress

There are multiple ways to handle this.

1. Simple meta field.

WordPress has these two filter.

  1. attachment_fields_to_edit : Core reference.
  2. attachment_fields_to_save : Core reference.

Using that we can add a custom field to the attachment, That will take care of adding the field all locations.

https://gist.github.com/PatelUtkarsh/bb2270493225a63c74b3ca590b9a4e9c.js

2. For more complex fields.

If you want more control on the field you can look at https://gist.github.com/thomasgriffin/4953041

That will require different and additional hooks, it would need to handle meta field at different locations like for media edit page ( post.php?post=1&action=edit ) additional code will be needed.

Required hooks:

  1. wp_ajax_save-attachment – To save an attachment meta on ajax request.
  2. print_media_templates – To print media template. See https://gist.github.com/thomasgriffin/4953100
  3. wp_prepare_attachment_for_js – To return our custom field data to the attachment.
  4. wp_enqueue_media to enqueue script.


Comments

Leave a Reply

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