如何在附件编辑器中添加复选框元素

时间:2010-11-18 作者:Scott B

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

注:"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); 

2 个回复
最合适的回答,由SO网友:prettyboymp 整理而成

将“输入”设置为“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;
}
保存的工作方式与上面所做的一样,但您是在对照复选框值进行检查,因此需要在isset()时更新为true,否则更新为false。

SO网友:Mathieu Clerte

下面是添加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美分。

结束

相关推荐