问题描述

下面的代码将一个自定义输入字段添加到附件编辑器。如何将文本输入转换为复选框,并获取/设置加载复选框的值并保存?

注意:"input" => "checkbox"不工作:(

function image_attachment_fields_to_edit($form_fields, $post) {  
        $form_fields["imageLinksTo"] = array(  
            "label" => __("Image Links To"),  
            "input" => "text",
            "value" => get_post_meta($post->ID, "_imageLinksTo", true)  
        );    
        return $form_fields;  
    }  

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); 

最佳解决方案

将’input’ 设置为’html’,并输出输入的 html:

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;
}

保存工作正如上面所述,但是您正在检查复选框值,因此您需要更新为 true if isset() 并将其更新为 false(如果不是) 。

次佳解决方案

以下是添加 IsLogo 复选框的完整块,包括保存:

function attachment_fields_to_edit_islogoimage( $form_fields, $post ) {
    $islogo = (bool) get_post_meta($post->ID, '_islogo', true);
    $checked = ($islogo) ? 'checked' : '';

    $form_fields['islogo'] = array(
        'label' => 'Logo Image ?',
        'input' => 'html',
        'html' => "<input type='checkbox' {$checked} name='attachments[{$post->ID}][islogo]' id='attachments[{$post->ID}][islogo]' />",
        'value' => $islogo,
        'helps' => 'Should this image appear as a proposal Logo ?'
    );
    return $form_fields;

}
add_filter( 'attachment_fields_to_edit', 'attachment_fields_to_edit_islogoimage', null, 2 );

function attachment_fields_to_save_islogoimage($post, $attachment) {
    $islogo = ($attachment['islogo'] == 'on') ? '1' : '0';
    update_post_meta($post['ID'], '_islogo', $islogo);  
    return $post;  
}
add_filter( 'attachment_fields_to_save', 'attachment_fields_to_save_islogoimage', null, 2 );

我的 2 美分

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。