测试 WordPress `update_option()` 中的错误

问题描述 投票:0回答:1

对于所有专家级 WP 主题开发人员来说,当使用多个

update_option()
时,有没有办法测试是否有任何更新不起作用(无论是通过连接错误还是通过验证),从而引发错误?

如果出现错误,之前的所有

update_option()
代码是否可以被忽略?

wordpress wordpress-theming
1个回答
4
投票
如果由于任何原因更新失败,update_option() 将返回 false。但是,当选项已设置为您尝试将其更新到的值时,它也会返回 false。

因此,您最好首先使用 get_option 检查该选项是否需要更新或是否存在,然后如果需要更新,则更新它。

如果您的选项未通过验证测试,则只需中断您正在使用的任何验证函数即可。你可以抛出一个 Wp_Error ,但这似乎太侵入性了。我倾向于使用 add_settings_error 并以这种方式向我的用户显示错误。

要回滚之前的任何 update_option 调用,需要将之前的值存储在数组中,然后如果需要恢复选项,则迭代它们。

通常我使用一个选项表条目来处理主题选项或插件选项等内容。没有什么比得到一个主题污染了我的选项表并为每个设置提供一个新选项更糟糕的了。

编辑:

以下是我如何处理主题选项和插件页面的选项验证。它基于类,因此如果您使用过程方法,则必须交换一些变量。

public function theme_options_validate( $input ) { if ($_POST['option_page'] != $this->themename.'_options') { add_settings_error($this->themename.'_theme_options', 'badadmin', __('<h3><strong>Smack your hands!</strong></h3> - You don\'t appear to be an admin! Nothing was saved.', $this->textDom), 'error'); return $input; } if ( empty($_POST) && !wp_verify_nonce($_POST[$this->themename.'_options'],'theme_options_validate') ) { add_settings_error($this->themename.'_theme_options', 'badadmin', __('<h3><strong>Smack your hands!</strong></h3> - You don\'t appear to be an admin! Nothing was saved.', $this->textDom), 'error'); return $input; } //begin validation - first get existing options - if any $init_themeoptions = get_option( $this->themename.'_theme_options' ); //create an array to store new options in $newInput = array(); //check to see if the author param has been set if($input[$this->shortname.'_meta-author'] !== '') { $newInput[$this->shortname.'_meta-author'] = wp_filter_nohtml_kses( $input[$this->shortname.'_meta-author] ); }else{ add_settings_error($this->themename.'_theme_options', 'emptydata', __('Oops - Author cant be empty'.', $this->textDom), 'error'); } //finally we see if any errors have been generated if(get_settings_errors($this->themename.'_theme_options')){ //if there are errors, we return our original theme options if they exist, otherwise we return the input data //this clause handles the situation where you have no theme options because its your themes first run if($init_themeoptions != false) { return $init_themeoptions; }else{ return $input; } } //if there were no errors we return the sanitized $newInput array and indicate successful save of data using settings error class, but //we don't use the error attribute, which isnt all that intuitiive add_settings_error($this->themename.'_theme_options', 'updated', __('<em>Success! </em> '.ucfirst($this->themename).' Theme Options updated!', $this->textDom), 'updated'); return $newInput; }

要在主题选项 ui 中显示设置错误,请将以下行添加到生成选项表单的位置;

settings_errors( $this->themename.'_theme_options' );

是的,选项表已经存在。我的意思是,您不必为每个主题选项在选项表中生成一个新条目,而是将它们全部包装在一个选项条目中。这也使得验证选项数据变得更加容易。

© www.soinside.com 2019 - 2024. All rights reserved.