How to Display Custom Error Messages in WordPress Admin

There are many ways to display custom error messages in WordPress. You must have often seen WordPress display error messages in the admin area. Nags to update to the latest release, for example. Various plugins also inject their custom messages highlighting new features or asking you to take action.

In this article, I’ll show you how to display a custom error message in the WordPress editor after checking for a condition. You can easily modify this code to cater to your requirements. Let’s say you want to warn the user to update to the latest theme or plugin version or warn them of a conflict.

Display Custom Error Messages in WordPress via the “notice” and “notice-error” class

To display a custom error message in the WordPress admin, you need to echo a <div> element containing the following:

  1. The “notice” class
  2. At least one of the following classes: notice-error, notice-warning, notice-success, notice-info

Optionally, the <div> can also contain the “is-dismissible” class, which adds a cross to the end of the message, allowing you to dismiss the notice.

Here’s how it works. Open up functions.php or your plugin for custom PHP code and paste in the following:

function admin_warning($messages) {
    
    // Write some conditional logic here
    
    $notice = <<<EOT
<div class="notice notice-error">
        <p>Warning notice!</p>
    </div>
EOT;
	
	echo $notice;

}
add_action( 'admin_notices', 'admin_warning');

If you don’t know how to add code like this, check out my earlier tutorial on inserting WordPress code snippets. In this code, we do the following:

  1. Hook into the admin screen with the “admin_notices” action hook
  2. Write some conditional logic
  3. Display the error <div> with the “notice” and “notice-error” class

This will create the following error message, as shown in this screenshot:

Custom Error Message in WordPress Admin
Custom Error Message in WordPress Admin

You can see that the custom error message displayed in the WordPress admin looks precisely like the notifications WordPress displays to you when something goes wrong. You can read more about the types of messages and the color coding of the notice class in WordPress. The “notice-success” class has a different color coding and shows a green highlight instead of red. You can also write your own CSS to modify the appearance of the warning notice.

This technique to display custom error messages in WordPress can be used for showing them anywhere – not just on the admin screen – you can also generate the messages in the post editor based on various conditionals.

About Bhagwad Park

I've been writing about web hosting and WordPress tutorials since 2008. I also create tutorials on Linux server administration, and have a ton of experience with web hosting products. Contact me via e-mail!

Speak Your Mind

*

WP-Tweaks