WordPress: How to display admin notices

October 15, 2012

You have probably seen the yellow and red notices on the top of the wp-admin area, either when updating a page, catching an error on a form, or a plugin poking at you to configure it after activation. These notices are very powerful ways to get a user’s attention and you may be wondering how to incorporate them into your own WordPress plugin. Well today is your lucky day because I am going to show you how to do just that! It is actually so simple you may find yourself scratching your head after reading this wondering why you never used it before.

It’s all about the CSS

Really, the CSS is what matters in this equation. There are a couple classes that when placed on a div will automagically position and colorize the admin notice text. Here are the two you should be keeping in mind:

  • updated – The yellow notice, usually used for informational messages such as updates
  • error – The red notice, typically associated with an action required on the part of the user

Do you like fishing? Set your hook

WordPress utilizes a series of hooks called actions and filters that allow you to tap into various parts of the core as it is running and alter functionality. There is an action hook specifically for admin notices called admin_notices. Pretty clever eh? To tap into this hook you simply pass two parameters to add_action(), the first is the hook name, the second the name of your function to run when the hook is called. I.E:

add_action( 'admin_notices', 'bl_admin_notice' );

Yellow brick road

Hopefully the yellow notice is what you see in your wp-admin area most often. The yellow notice typically signifies an informational message to the user. A couple core examples are saving/updating a post success message and de/activating plugins. To display a yellow notice create a <div> with the class of updated inside the function you setup previous.

function bl_admin_notice() {
    echo "
This is a yellow message
"; }

Danger Will Robinson! Danger!

Red notices can sometimes be scary in WordPress, but in general WordPress is solid and stable enough that the red notices have generally become associated with a required user action, such as a notice letting the user know they need to configure a plugin after activating it. It may come as a shock, but the red notice is just as hard as the yellow notice to setup.

function bl_admin_notice() {
    echo "
This is a red message
"; }

That’s all folks

It really is as easy as that. Now go forth and notify your plugins.

Leave a Reply

Your email address will not be published. Required fields are marked *