遵循开发人员文档中的方法selected() 但无法使其与媒体库中的自定义字段一起用于选择列表。
它不会保存价值,也不会变成;已选定;。看起来WP正在后台执行一些js/ajax,所以我需要以不同的方式来处理这个问题,还是有一个愚蠢的拼写错误?
请参阅下面的代码,非常感谢您的帮助。
/*
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);