使用WordPress(内置)错误处理return;
如果某些用户输入错误。向他们提供一些信息,说明做得不对。
function some_example_fn( $args = array() )
{
// If value was not set, build an error message
if ( ! isset( $args[\'some_value\'] ) )
$error = new WP_Error( \'some_value\', sprintf( __( \'You have forgotten to specify the %1$s for your function. %2$s Error triggered inside %3$s on line %4$s.\', TEXTDOMAIN ), \'$args[\\\'some_value\\\']\', "\\n", __FILE__, __LINE__ ) );
// die & print error message & code - for admins only!
if ( isset( $error ) && is_wp_error( $error ) && current_user_can( \'manage_options\' ) )
wp_die( $error->get_error_code(), \'Theme Error: Missing Argument\' );
// Elseif no error was triggered continue...
}
一个错误(对象)针对所有主题或插件,您可以在引导过程中为主题或插件设置一个全局错误对象:
function bootstrap_the_theme()
{
global $prefix_error, $prefix_theme_name;
// Take the theme name as error ID:
$theme_data = wp_get_theme();
$prefix_theme_name = $theme_data->Name;
$prefix_error = new WP_Error( $theme_data->Name );
include // whatever, etc...
}
add_action( \'after_setup_theme\', \'bootstrap_the_theme\' );
以后,您可以根据需要添加无限错误:
function some_theme_fn( $args )
{
global $prefix_error, $prefix_theme_name;
$theme_data = wp_get_theme();
if ( ! $args[\'whatever\'] && current_user_can( \'manage_options\' ) ) // some required value not set
$prefix_error->add( $prefix_theme_name, sprintf( \'The function %1$s needs the argument %2$s set.\', __FUNCTION__, \'$args[\\\'whatever\\\']\' ) );
// continue function...
}
然后你可以在主题结束时把它们全部取出来。这样,您就不会中断页面的呈现,并且仍然可以输出所有错误以进行开发
function dump_theme_errors()
{
global $prefix_error, $prefix_theme_name;
// Not an admin? OR: No error(s)?
if ( ! current_user_can( \'manage_options\' ) ! is_wp_error( $prefix_error ) )
return;
$theme_errors = $prefix_error->get_error_messages( $prefix_theme_name );
echo \'<h3>Theme Errors</h3>\';
foreach ( $theme_errors as $error )
echo "{$error}\\n";
}
add_action( \'shutdown\', \'dump_theme_errors\' );
有关更多信息,请访问
this Q. 修复“协作”的相关票据
WP_Error
和
wp_die()
从那里链接,然后会有另一张票。评论、批评和;这是值得赞赏的。