How to Add Additional Fields to the WordPress Media Uploader

Say, for example, that you want to add the ability to add a YouTube link to a media file.

function show_media_extra_attachment_fields($form_fields, $post) {
    $form_fields['youtube_link'] = array(
        'label' => 'YouTube link',
        'input' => 'text',
        'value' => get_post_meta($post->ID, 'youtube_link', true),
        'helps' => 'If provided, a youtube video will be added',
    );
    return $form_fields;
}

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

function save_media_extra_attachment_fields($post, $attachment) {
    if (isset($attachment['youtube_link']))
        update_post_meta($post['ID'], 'youtube_link', $attachment['youtube_link']);
    return $post;
}

add_filter('attachment_fields_to_save', 'save_media_extra_attachment_fields', 10, 2);

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

$youtube_link = get_post_meta($post->ID, 'youtube_link', true);

Learning Resources

wpbeginner – How to Add Additional Fields to the WordPress Media Uploader