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. All works great. What isn't really working is using the admin_notices hook to display any error / update messages. I'me guessing I can't call that hook from within the add_menu_page function? If so how are you suppose to handle errors on custom pages in OOP plugins?
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;
}
}
}
}