Getting admin notices working for plugin errors

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.