不要每次都使用add\\u settings\\u section()和add\\u settings\\u field(),而是创建一个返回选项数组的函数,例如:
function my_theme_options() {
$options = array();
$options[] = array(
\'id\' => \'ID\',
\'title\' => \'Title\',
\'type\' => \'text_field\', // use this value to sanitize/validate input
\'validate\' => \'url\' // use this value to validate the text as url
// add as much as you need like description, default value ...
);
$options[] = array(
\'id\' => \'ID_2\',
\'title\' => \'Title\',
\'type\' => \'text_field\',
\'validate\' => \'email\' // use this value to validate the text as email
// add as much as you need like description, default value ...
);
// every time you want to add a field you\'ll use this function an create a new array key $options[] = array();
return $options;
}
使用此函数,我们可以向foreach循环注册每个字段,该循环将使用add\\u settings\\u field()
现在,使用此函数,您可以为register\\u setting()创建一个回调函数,并使用switch验证输入,例如:
// this should be the callback function of register_setting() (last argument)
function validate_settings($input) {
$options = my_theme_options(); // we\'ll set $options variable equal to the array we created in the function before
$valid_input = array(); // this will be the array of the validated settings that will be saved to the db, of course using one array for all options.
foreach ($options as $option) {
switch ( $option[\'type\'] ) { // $option[\'type\'] where type is the key we set before in my_theme_options()
case \'text_field\':
// inside we\'ll create another switch that will use the validate key we created in my_theme_options()
switch( $option[\'validate\'] ) {
case \'url\':
// validate url code
break;
case \'email\':
// validate email
break;
// create a default for regular text fields
default:
// default validation
break;
}
break;
case \'textarea\':
// your validation code here
break;
// you get the idea just keep creating cases as much as you need
}// end switch
}// end foreach
return $valid_input;
}
在每个案例结束时,将值保存到$valid\\u输入数组
$valid_input[$option[\'id\']] = $input[$option[\'id\']]
例如,验证url使用:
if ( preg_match(\'your regex\', $input[$option[\'id\']]) ) {
$valid_input[$option[\'id\']] = $input[$option[\'id\']];
}
您也可以像options函数一样创建一个函数,但对于sections和创建一个foreach循环,该循环将使用add\\u settings\\u section(),您会觉得这对您来说会容易得多,以后要添加新的设置字段和section时会节省很多时间。希望有帮助:)