我试图保存是否选中了媒体上传器弹出窗口中的复选框,以便我可以从前端检索它。
我正在使用以下代码:
function filter_attachment_fields_to_edit( $form_fields, $post ) {
$foo = (bool) get_post_meta($post->ID, \'foo\', true);
$form_fields[\'foo\'] = array(
\'label\' => \'Is Foo\',
\'input\' => \'html\',
\'html\' => \'<label for="attachments-\'.$post->ID.\'-foo"> \' . \'<input type="checkbox" id="attachments-\'.$post->ID.\'-foo" name="attachments[\'.$post->ID.\'][foo]" value="1"\'.($foo ? \' checked="checked"\' : \'\').\' /> Yes</label> \',
\'value\' => $foo,
\'helps\' => \'Check for yes\'
);
return $form_fields;
}
从这个问题:
How to add a checkbox element to attachments editor with example我必须承认,我不完全理解这段代码是如何组合在一起的。我尝试使用此功能保存:
function image_attachment_fields_to_save($post, $attachment) {
if( isset($attachment[\'imageLinksTo\']) ){
update_post_meta($post[\'ID\'], \'_imageLinksTo\', $attachment[\'imageLinksTo\']);
}
return $post;
}
add_filter("attachment_fields_to_edit", "image_attachment_fields_to_edit", null, 2);
add_filter("attachment_fields_to_save", "image_attachment_fields_to_save", null, 2);
最合适的回答,由SO网友:Bainternet 整理而成
字段id必须在两个函数中都匹配,因此如果您的字段id为foo
保存时,需要查找该id;保存复选框时,如果未设置此复选框,则可将其删除:
function image_attachment_fields_to_save($post, $attachment) {
if( isset($attachment[\'foo\']) ){
update_post_meta($post[\'ID\'], \'foo\', $attachment[\'foo\']);
}else{
delete_post_meta($post[\'ID\'], \'foo\' );
}
return $post;
}
add_filter("attachment_fields_to_save", "image_attachment_fields_to_save", null, 2);