Custom field in media library not saving, selected() function not adding “selected” to select list input type

Question

Following the approach in the developer docs for selected() but can’t get it to work with a custom field in the media library for a select list.

It won’t save the value, or become “selected”. Looks like WP is doing some js/ajax in the background here, so do I need to approach this differently or have a dumb typo?

Please see code below, help is appreciated.

/*
Add license field to media attachments 
*/

    function add_custom_field_license( $form_fields, $post ) {
        $license_field = get_post_meta($post->ID, 'license_field');
        $form_fields['license_field'] = [
            'label' => 'License',
            'input' => 'html',
            'html' => "<select name='attachments[{$post->ID}][license_field]' id='attachments-{$post->ID}-license_field'> 
        <option value='none' " . selected($license_field, "none") . ">None (all rights reserved)</option>
        <option value='CC0' " . selected($license_field, "CC0") . ">CC0</option>
        <option value='CC BY' " . selected($license_field, "CC BY") . ">CC BY</option>
        </select>",
        ];
        return $form_fields;
    }
    add_filter('attachment_fields_to_edit', 'add_custom_field_license', null, 2); 



/*
Save license field to media attachments
*/
function save_custom_field_license($post, $attachment) {  
    if( isset($attachment['license_field']) ){  
        update_post_meta($post['ID'], 'license_field', sanitize_text_field( $attachment['license_field'] ) );  
    }else{
         delete_post_meta($post['ID'], 'license_field' );
    }
    return $post;  
}
add_filter('attachment_fields_to_save', 'save_custom_field_licenser', null, 2);
0
, , , user191367 3 years 2020-07-09T19:10:33-05:00 0 Answers 76 views 0

Leave an answer

Browse
Browse