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. 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;
            }
        }
    }
}

Related posts

Leave a Reply

1 comment

  1. Admin Notices are not used for this and the hook don’t work at the point where you’re putting it. And to trigger it selectively, we use get_option or 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.

    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.