设置API出错时保留旧值

时间:2017-06-15 作者:sanjay ojha

当窗体未能通过register\\u设置的sanitize回调中定义的验证时,我试图保留窗体的旧值。但它不这样做,而是保存默认值

register_setting(\'setting-wpse3401\', \'wpse3401_options\', array( \'sanitize_callback\' => [$this, \'wpse3401_sanitize_value\']));

public function wpse3401_sanitize_value( $val )
{
    $newval = array();
    $type = \'updated\';
    $msg = \'Settings is saved!\';    

    $newval[\'form_field_0\'] = sanitize_text_field($val[\'form_field_0\']);
    if( $val[\'form_field_1\'] < 1 ) {
        $type = \'error\';
        $msg = \'Please enter number greater than 0\'
    } else {
        $newval[\'form_field_1\'] = $val[\'form_field_1\'];
    }

    add_settings_error(\'wpse3401_messages\', \'wpse3401_message\', __($msg, \'text-domain\'), $type);

    if($type == \'updated\'){
        return $newval;
    } else{
        return null;
    }
}

1 个回复
SO网友:Sean

不幸的是,WordPress没有将旧值作为附加参数提供给sanitize_callback 可调用。这通常由option validator hook that WordPress calls when saving the updated setting...

return apply_filters( "sanitize_option_{$option}", $value, $option, $original_value );
。。。但实际上it is not actually registered with any additional arguments when the filter is added during register_setting:

if ( ! empty( $args[\'sanitize_callback\'] ) ) {
    add_filter( "sanitize_option_{$option_name}", $args[\'sanitize_callback\'] );
}
因为add_filter 不指定可调用函数接受任何其他参数,apply_filter 不提供$option$original_value 在调用回调时返回(我认为这是一个bug,并提交了一个ticket 给开发商)。这意味着您不能使用$original_value 在提供的设置无效时使用。相反,我建议您在回调中获取当前设置的值:

if ( \'updated\' === $type ) {
    return $newval;
} else {
    // use previous value
    return get_option( \'wpse3401_options\' );
}

结束

相关推荐

get_terms return errors

嗨,当我尝试get_terms(); 通过此代码在主题选项中$catalogs_terms = get_terms( \'catalogs\' ); $mycatalogs = array( -1 => \'Select a catalog\' ); if ( $catalogs_terms ) { foreach ( $catalogs_terms as $catalog_term ) { $mycatalogs[$cata