[英]Using WordPress admin_notices in a OOP plugin
I've registered a new admin page in WordPress where I display out output HTML and format and validate some input and save to the DB. 我在WordPress中注册了一个新的管理页面,在那里我显示输出HTML和格式并验证一些输入并保存到数据库中。 All works great. 一切都很棒。 What isn't really working is using the admin_notices hook to display any error / update messages. 什么不是真正有效的是使用admin_notices钩子来显示任何错误/更新消息。 I'me guessing I can't call that hook from within the add_menu_page function? 我猜我不能在add_menu_page函数中调用那个钩子? If so how are you suppose to handle errors on custom pages in OOP plugins? 如果是这样,您如何处理OOP插件中自定义页面上的错误?
I've included a very stripped down version of the code below. 我在下面列出了一个非常精简的代码版本。
class Fitems_Admin {
public $admin_notices = array();
public function __construct(){
// Register Menus
add_action( 'admin_menu', array( $this, 'register_menus' ) );
}
public function register_menus(){
add_menu_page( 'fItems', 'fItems', 'administrator', 'fItems', array( $this, 'items' ) );
}
public function items(){
// do stuff, validate input & register any errors, example below
$this->admin_notices['updated'][] = __( 'item(s) successfully deleted.', 'fItems' );
// Register errors
add_action( 'admin_notices', array( $this , 'display_admin_notices' ) );
// display output;
echo $output;
}
// Just formats and echos any errors in the $this->admin_notices array();
public function display_admin_notices( $return = FALSE ){
if( ! empty( $this->admin_notices ) ){
// Remove an empty and then sort
array_filter( $this->admin_notices );
ksort( $this->admin_notices );
$output = '';
foreach( $this->admin_notices as $key => $value ){
// Probably an array but best to check
if( is_array( $value ) ){
foreach( $value as $v ){
$output .= '<div class="' . esc_attr( $key ) . '"><p>' . esc_html( $v ) . '</p></div>';
}
} else {
$output .= '<div class="' . esc_attr( $key ) . '"><p>' . esc_html( $value ) . '</p></div>';
}
}
if( $return ){
return $output;
} else {
echo $output;
}
}
}
}
Admin Notices are not used for this and the hook don't work at the point where you're putting it. Admin Notices不用于此,并且钩子在您放置它时不起作用。 And to trigger it selectively, we use get_option
or get_user_meta
. 为了有选择地触发它,我们使用get_option
或get_user_meta
。
For this kind of notice , we use admin classes: 对于这种通知 ,我们使用管理类:
if( $success )
echo '<div class="updated"><p>class .updated with paragraph</p></div>';
if( $error )
echo '<div class="error"><p>class .error with paragraph</p></div>';
Here's a helper plugin to style our admin screens: WordPress Admin Styles . 这是一个帮助我们管理屏幕样式的帮助插件: WordPress管理样式 。
Or, use the whole Settings API , which has a function add_settings_error()
to display notices, despite the name, it is used to display update
and error
messages. 或者,使用整个Settings API ,它具有add_settings_error()
函数来显示通知,尽管名称,它用于显示update
和error
消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.