我在为 wordpress 添加自定义设置页面时遇到问题,更具体地说是获取保存选项。
这方面的文档似乎缺乏且不一致,因为不同的示例和不同的不同功能对同一事物的解释不同。
wordpress codex 上的最新示例使用 sanitize 回调函数来保存选项。但是 add_settings_field() 文档说保存选项应该在幕后进行。无论如何使用 san 回调来保存似乎很奇怪。
我尝试了各种不同的方法,有一次我的代码设法保存了其中一个字段,但不是全部。
我当前的代码:
class wwtkSettings {
public function __construct() {
if ( is_admin() ){
add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
add_action( 'admin_init', array( $this, 'page_init' ) );
}
}
public function add_plugin_page(){
add_options_page( 'WWTK Settings', 'WWTK settings', 'manage_options', 'wwtk-settings', array( $this, 'create_admin_page' ) );
}
public function create_admin_page() {
?>
<div class="wrap">
<?php screen_icon(); ?>
<h2>WWTK Settings</h2>
<form method="post" action="options.php">
<?php
settings_fields( 'wwtk-setting-group' );
do_settings_sections( 'wwtk-settings' );
?>
<?php submit_button(); ?>
</form>
</div>
<?php
}
public function page_init() {
register_setting( 'wwtk-setting-group', 'wwtk-setting-group', array( $this, 'wwtk_validate_options' ) );
add_settings_section(
'wwtk-settings-section',
'Categories and pages',
array( $this, 'print_section_info' ),
'wwtk-settings'
);
add_settings_field(
'frontpage',
'Frontpage category:',
array( $this, 'create_category_field' ),
'wwtk-settings',
'wwtk-settings-section',
'frontpage'
);
add_settings_field(
'category1',
'Category & page 1',
array( $this, 'create_category_field' ),
'wwtk-settings',
'wwtk-settings-section',
'category1'
);
add_settings_field(
'category2',
'Category & page 2',
array( $this, 'create_category_field' ),
'wwtk-settings',
'wwtk-settings-section',
'category2'
);
add_settings_field(
'category3',
'Category & page 3',
array( $this, 'create_category_field' ),
'wwtk-settings',
'wwtk-settings-section',
'category3'
);
}
//TODO: check if category and page exist. and sanitize!
public function wwtk_validate_options( $input ) {
return $input;
}
public function print_section_info(){
print 'Enter the names of categories that should be displayed on the page with the same name(both must exist):';
}
public function create_category_field($args){
?><input type="text" id="<?php echo $args ?>" name="wwtk-setting-group" value="<?php echo get_option( 'wwtk-setting-group['.$args.']' ); ?>" /><?php
}
}