Saving Custom Field in Attachment Window in WordPress 3.5

I wanted to be able to add author information to my attachments and merged this code: http://www.billerickson.net/wordpress-add-custom-fields-media-gallery/ with the one you refer to. I Got it to work fully in the modal window via AJAX. The modified code is as follows:

/**
 * Add Author 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 admin_attachment_field_media_author_credit( $form_fields, $post ) {

    $form_fields['media-author-name'] = array(
        'label' => 'Author Name',
        'input' => 'text',
        'value' => get_post_meta( $post->ID, 'media_author_name', true )
        //'helps' => 'If provided, author credit will be displayed'
    );

    $form_fields['media-author-url'] = array(
        'label' => __('Author URL',b()),
        'input' => 'text',
        'value' => get_post_meta( $post->ID, 'media_author_url', true ) 
        //'helps' => 'If provided, the author credit will be linked'
    );

    return $form_fields;

} add_filter( 'attachment_fields_to_edit', 'admin_attachment_field_media_author_credit', 10, 2 );

/**
 * Save values of Author 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 admin_attachment_field_media_author_credit_save( $post, $attachment ) {

    if( isset( $attachment['media-author-name'] ) )
        update_post_meta( $post['ID'], 'media_author_name', $attachment['media-author-name'] );

    if( isset( $attachment['media-author-url'] ) )
        update_post_meta( $post['ID'], 'media_author_url', $attachment['media-author-url'] );

    return $post;

} add_filter( 'attachment_fields_to_save', 'admin_attachment_field_media_author_credit_save', 10, 2 );

/**
 * Save values of Author Name and URL in media uploader modal via AJAX
 */

function admin_attachment_field_media_author_credit_ajax_save() {

    $post_id = $_POST['id'];

    if( isset( $_POST['attachments'][$post_id]['media-author-name'] ) )
        update_post_meta( $post_id, 'media_author_name', $_POST['attachments'][$post_id]['media-author-name'] );

    if( isset( $_POST['attachments'][$post_id]['media-author-url'] ) )
        update_post_meta( $post_id, 'media_author_url', $_POST['attachments'][$post_id]['media-author-url'] );

    clean_post_cache($post_id);

} add_action('wp_ajax_save-attachment-compat', 'admin_attachment_field_media_author_credit_ajax_save', 0, 1); 

Hope this was helpful!

P.S. The next challenge will be to append this to images uploaded in the document. D.S.

Leave a Comment