Adding custom fields to attachments

WordPress has extended functionality that allows to create media library. As WordPress developers sometimes we need add custom fields to library items. Today I would like to describe how to add custom fields to attachments.

1. Add the code that displays custom field on media library popup window and on edit media page. Insert this piece of code into your plugin file (if you develop plugin) or into function.php (if you develop theme).

/* Add custom field to attachment */
function my_image_attachment_add_custom_fields($form_fields, $post) {
	$form_fields["image-gallery-url"] = array(
		"label" => __("Image URL"),
		"input" => "text",
		"value" => get_post_meta($post->ID, "image-gallery-url", true),
		"helps" => __(""),
	);
	return $form_fields;
}
add_filter("attachment_fields_to_edit", "my_image_attachment_add_custom_fields", null, 2);

2. Handle library item updating. Insert this piece of code into your plugin file (if you develop plugin) or into function.php (if you develop theme).

/* Save custom field value */
function my_image_attachment_save_custom_fields($post, $attachment) {
	if(isset($attachment['image-gallery-url'])) {
		update_post_meta($post['ID'], 'image-gallery-url', $attachment['image-gallery-url']);
	} else {
		delete_post_meta($post['ID'], 'image-gallery-url');
	}
	return $post;
}
add_filter("attachment_fields_to_save", "my_image_attachment_save_custom_fields", null , 2);

That’s it..