当你打电话的时候register_setting
, 第三个参数是sanitize回调函数。您可以在该函数中执行所需的任何数据操作,以便将用户输入安排为代码所需的格式。因此,在数据验证之后(整数是整数,清理文本字段等),您可以检索当前选项值,并根据用户输入从中添加或删除。
您还可以在提交数据之前在javascript中进行一些操作,但请注意,javascript可以关闭,因此您必须处理两种不同类型的输入。因此,这通常不是一个好主意。
下面的代码在页面中使用javascript创建和删除列表中的项目,并在单击保存按钮时将整个列表放入一个输入中。该插件依赖于javascript获取该输入的内容,并以JSON格式保存(在PHP中没有操作,只有javascript)。sanitize回调创建一个数组数组,以便用户可以保存多个命名列表。这与你的问题不太一样,但相似且经过测试。
register_setting( \'example_group\', \'example_option_name\', \'example_settings_validation\' );
function example_settings_defaults( $theme ) { // provide default option values
if ( \'weaver-ii\' == $theme )
$page = \'themes.php?page=WeaverII\';
else if ( \'aspen\' == $theme )
$page = \'themes.php?page=Aspen\';
else $page = \'\';
$label = \'new\';
$used = sanitize_key( $label );
$entry = array( \'color_class\'=>\'color\', \'user_label\'=>$label, \'last_modified\'=>\'\', \'tie_list\'=>json_encode( array() ) );
$new = array( \'theme_page\'=>$page, \'last_used\'=>$used, \'entries\'=>array() );
$new[\'entries\'][$used] = $entry;
return $new;
}
function example_settings_validation( $input ) { // called by Settings API on a Save
$clean = get_option( \'example_option_name\', example_settings_defaults() );
$label = sanitize_text_field( $input[\'user_label\'] );
if ( isset( $input[\'action_delete\'] ) ) { // user clicked Delete list
if ( isset( $input[\'user_label\'] ) ) {
$key = sanitize_key( $label );
unset( $clean[\'entries\'][$key] );
if ( 0 == count( $clean[\'entries\'] ) ) {
$new = example_settings_defaults( \'xx\');
$clean[\'entries\'] = $new[\'entries\'];
$clean[\'last_used\'] = $new[\'last_used\'];
}
else if ( $key == $clean[\'last_used\'] ) { // check if they deleted last used
$keys = array_keys( $clean[\'entries\'] );
$clean[\'last_used\'] = $keys[0];
}
add_settings_error(\'deleteID\', \'action_delete\', $label.__(\' entry deleted.\', \'xmpl\'), \'updated\');
}
}
if ( isset( $input[\'action_save\'] ) ) { // user clicked Save
$clean[\'theme_page\'] = sanitize_text_field( $input[\'theme_page\'] );
$entry = array();
$entry[\'color_class\'] = sanitize_html_class( $input[\'color_class\'] );
$entry[\'tie_list\'] = sanitize_text_field( $input[\'tie_list\'] );
$entry[\'last_modified\'] = current_time( \'mysql\' );
if ( empty( $label ) ) $label = \'new\';
$entry[\'user_label\'] = $label;
$clean[\'last_used\'] = sanitize_key( $label );
$clean[\'entries\'][$clean[\'last_used\']] = $entry;
add_settings_error(\'saveID\', \'action_save\', $label.
sprintf( _x(\' entry saved at %s\',\'MySQL timestamp\', \'xmpl\'), $entry[\'last_modified\'] ), \'updated\');
}
return $clean;
}