我正在使用underscores (_s) theme 要构建一个主题选项页面,我在页面上有一组复选框。在下面的示例中,为了简单起见,我只包含了2个。
我的问题是:
保存时,下面的checked()函数中有什么使每个复选框保持选中状态?我必须对照DB中的值检查每个值是否正确
// register setting
register_setting(
\'options\', // Options group
\'theme_options\', // Database option
\'theme_options_validate\' // The sanitization callback, see below
);
// add settings field
add_settings_field(
\'post_sharing_networks\',
\'Post Sharing Networks To Show\',
\'settings_field_post_sharing_networks\', // callback below
\'theme_options\',
\'general\'
);
// set up the array
// more will be added later. 2 shown here for simplicity
function post_sharing_networks() {
$post_sharing_networks = array(
\'twitter\' => array(
\'value\' => \'twitter\',
\'label\' => \'Twitter\'
),
\'facebook\' => array(
\'value\' => \'facebook\',
\'label\' => \'Facebook\'
),
);
return $post_sharing_networks;
}
// callback
function settings_field_post_sharing_networks() {
$options = get_option( \'theme_options\' ); // get array of all the theme options
$post_sharing_networks = $options[\'post_sharing_networks\']; // this will get array for just the post sharing networks
// eg
/*
array (size=2)
\'twitter\' => string \'1\' (length=1)
\'facebook\' => string \'1\' (length=1)
*/
// builds the checkbox list form the post_sharing_networks() function
foreach ( post_sharing_networks() as $network ) { ?>
<label>
<input type="checkbox" value="1" name="theme_options[post_sharing_networks][<?php echo esc_attr( $network[\'value\'] ); ?>]" <?php checked( /* what goes in here for this to work? */ ); ?> />
<?php echo $network[\'value\']; ?>
</label>
<?php }
}
// sanitization callback
function theme_options_validate( $input ) {
$output = array();
// how do I properly sanitize the checkbox group?
// it saves the checkboxes to DB fine currently but I think it can be improved
$options = get_option( \'theme_options\' );
foreach ( post_sharing_networks() as $network ) {
if ( isset( $options[\'post_sharing_networks\'] ) )
$output[\'post_sharing_networks\'] = $input[\'post_sharing_networks\'];
}
return apply_filters( \'theme_options_validate\', $output, $input );
}
这是保存到wp\\U选项表中时的外观s:21:"post_sharing_networks";a:2:{s:7:"twitter";s:1:"1";s:8:"facebook";s:1:"1";}