根据注释中的概述,通过在我的保存功能中修复一个输入错误,并在中设置第三个参数get_post_meta()
为真,为假selected()
它很有魅力。谢谢大家!
如果有人试图将“选择列表”自定义字段添加到他们的媒体管理器中,以下是工作代码:
/*
Add license field to media attachments
*/
function add_custom_field_license( $form_fields, $post ) {
$license_field = get_post_meta($post->ID, \'license_field\', true);
$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", false) . ">None (all rights reserved)</option>
<option value=\'CC0\' " . selected($license_field, "CC0", false) . ">CC0</option>
<option value=\'CC BY\' " . selected($license_field, "CC BY", false) . ">CC BY</option>
<option value=\'CC BY-NC\' " . selected($license_field, "CC BY-NC", false) . ">CC BY-NC</option>
<option value=\'CC BY-SA\' " . selected($license_field, "CC BY-SA", false) . ">CC BY-SA</option>
<option value=\'CC BY-NC-ND\' " . selected($license_field, "CC BY-NC-ND", false) . ">CC BY-NC-ND</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_license\', null, 2);