How To Add Custom Fields To WordPress Media Uploader

If you’re a photographer or something like that, then you might wanna add copyright or some other custom fields to WordPress media uploader to customize your blog’s front-end or just for giving the original photographer some credits. WordPress stores images as posts in the attachment post type, so adding some custom data is like adding custom fields to attachment post type. Here’s how you can do that.

Just add following code, which comes from Bill Erickson, to the functions.php of your current theme or a site-specific plugin:

/**
 * 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 );

That’s it! Now your custom fields will appear in your media uploader and media gallery.

You can now call the custom field value in the loop with the following snippet:

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

Or if you wanna call the information in other theme files, then use the following snippet:

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

Leave a Reply

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