How to Make an admin_notices Message That Disappears Once the User Leaves That Particular Page?

The short answer is: Use Query Strings.

If you notice in the address bar immediately after you publish a Post… You will see something similar to this: domain.com/wp-admin/post.php?post=4935&action=edit&message=6

There’s a few different Query Variables:

  1. post contains the ID of the Post being edited.
  2. action is saying we’re currently “editing” the Post.
  3. message refers to what Admin Notice should be displayed depending on what was done to the Post.

Look here for an example on seeing the default Post Type messages and how to customize the messages (a/k/a Admin notices) specifically for your Custom Post Type.

The above example is relative to a Custom Post Type and WordPress handles all the conditionals for you. All you have to do is customize the messages.

If you wanted to do this on a custom settings page for your plugin for example. You would need to take several steps to accomplish the same thing.

In a nut shell:

Send the user to your custom settings page WITH an extra Query Variable appended to the URL.

Hook into admin_notices.

Inside the callback function you specify for the admin_notices hook, have an array of messages, where they array key will match the value of your Query Variable and the array value will be the appropriate message.

Check to see if your Query Variable is present. (Be sure to check that the user is specifically on your plugin’s setting page using: get_current_screen(); – otherwise you’ll be checking globally across every admin page.)

Perform additional conditional checks for the different possible values of your Query Variable and display the appropriate Admin Notice depending on the value of your Query Variable.

So basically:

  • Check if the user is on your plugin’s settings page.
  • Check if your Query Variable is present.
  • Check if the value of your Query Variable matches that of something
    expected.
  • Select appropriate message depending on the expected value matched
    from your Query Variable with an array key in your messages array.
  • Display Admin Notice with message matched from messages array key.

Leave a Comment