下面是我如何处理这个问题的。希望它能帮助别人。
/**
* Add a validation callback to the settings form
*/
public function options_update()
{
register_setting($this->plugin_name, $this->plugin_name, array($this, \'validate\'));
}
/**
* Validates and sanitizes the submitted values
* @param $input
* @return array
*/
public function validate($input)
{
$valid = array();
$valid[\'is_api_enabled\'] = (isset($input[\'is_api_enabled\']) && !empty($input[\'is_api_enabled\'])) ? 1 : 0;
$valid[\'api_key\'] = (isset($input[\'api_key\'])) ? $input[\'api_key\'] : \'\';
if ($valid[\'is_api_enabled\'] === 1) {
if (!$valid[\'api_key\'] || empty(trim($valid[\'api_key\']))) {
add_settings_error($this->plugin_name, \'api_key\', __(\'API key is mandatory if API is enabled\'));
$this->revert_setting($valid, $this->plugin_name, \'api_key\');
$this->revert_setting($valid, $this->plugin_name, \'is_api_enabled\');
}
}
// only return accepted values (old ones or correct)
return $valid;
}
/**
* Revert the submitted setting to its original value
* @param $new
* @param $option
* @param null $key
*/
private function revert_setting(&$new, $option, $key = null)
{
$old = get_option($option);
if ($key) {
$new[$key] = array_key_exists($key, $old) ? $old[$key] : null;
} else {
$new = $old;
}
}