Getting admin notices working for plugin errors

I’m beginning with creating plugins and I don’t quite understand the process of displaying error messages. e.g. I use the php readfile function to download a file from a hidden location. If something goes wrong e.g. the file isn’t found, how do you display a message at that moment.

I know you need to use add_action for ‘admin_notices’ but I can’t quite figure out where you are supposed to put the add_action calls.

Read More

As far as I can tell, you have to create a function my_download_file which tries the download and echo’s a <div class="error">. Then ‘somewhere’ you need to call add_action('admin_notices', 'my_download file');.

This, from reading the Action Reference, then gets called when admin_notices are being printed out. But does it always get called, or does it only get called when do_action gets called?

Related posts

Leave a Reply

1 comment

  1. What you need to do (as we discussed in comments) is run your conditional logic inside the function that that add_action calls. For example, you’re adding an action to the admin notices hook.

    The action will run, but the stuff inside that action’s callback will only run if you let it.

    add_action( 'admin_notices', 'your_custom_function' );
    
    function your_custom_function() {
    
        // You need some way to set (or retrieve) the value of your $error here (if not already set)
    
        if( $error ) {
            // Put everything here
        }
    
    }
    

    In a theme, this is typically found in your functions.php file or a file included in it. In a plugin, it could be in any file also as long as it is included in your main plugin file.