0

This is my code:

class App 
{
    
    public function run()
    {
        add_action('admin_menu', [$this, 'menu']);
        add_action('admin_notices', [$this, 'pip']);
    }

    public function menu()
    {
        echo 0;

        add_submenu_page(
            'tools.php',
            __('Tools', 'name-plugin'),
            __('Name', 'name-plugin'),
            'manage_options',
            'name-plugin',
            [$this, 'show']
        );
    }

    public function show()
    {
        echo 1;
    }

    public function pip() {
        echo 2;
    }
}

This code printed 021

But I want to print 012

Note: I want to put all add_action in run method

I used priority too, but it's not work:

add_action('admin_menu', [$this, 'menu'], 1);
add_action('admin_notices', [$this, 'pip'], 2);

If I put admin_notices in show method, this code works fine.

But I don't want put it in show method

11
  • 1
    I don't see anything wrong with seeing 021. I don't know why you'd expect anything different. Admin notices display at the top of the page. That's normal. Sep 13 at 8:45
  • Are you asking how to reposition the notices? Sep 13 at 8:47
  • @JacobPeattie no. I want to show errors from show method. But admin_notices run before show method and my error not showing
    – user212402
    Sep 13 at 8:52
  • Are you using the Settings API or something custom? Generally if you have a form in show(), the code that handles submission of that form should be in a separate function that's hooked earlier. Then it can pass any errors to the notices hook. Sep 13 at 8:54
  • 1
    admin notices aren't just echoing out text on the admin_notices hook, they have specific HTML that's needed
    – Tom J Nowell
    Sep 13 at 9:36
0

Those are not admin notices. It's not enough to echo text on the admin_notices hook, it needs to be wrapped in specific HTML.

Here is an example taken from the official WP doc for admin_notices:

function sample_admin_notice__success() {
    ?>
    <div class="notice notice-success is-dismissible">
        <p><?php _e( 'Done!', 'sample-text-domain' ); ?></p>
    </div>
    <?php
}
add_action( 'admin_notices', 'sample_admin_notice__success' );

If you need to add notices after the hook has fired, use the same HTML structure and WordPress will move it using javascript to the correct place

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.