If you’re in the business of building plugins, or even themes for that matter, and are incorporating object-oriented practices into your work then you’re likely faced with serialization of some type. And one of the aspects of serialization that it requires some type of feedback for the user.

This can be a success message, a failure message, or a message simply warning the user that some went wrong or perhaps something should be updated.

Whatever the case, WordPress provides all of the facilities that we need; however, we can make it even easier on ourselves by writing a helper function for admin notices. It’s simple, too.

Admin Notices: A Helper Function

When it comes to writing admin notices, it’s important to familiar with the appropriate hook.

Admin Notices

From there, you also need to know the following class names:

  • notice-error
  • notice-success
  • notice-warning
  • notice-info

With that, it’s possible to write a helper function that uses the above hook and an anonymous function (or a closure) to achieve exactly waht you need. But first note the following:

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

With that said, you should have everything you need to write your helper and have an idea as to when to empty it.

First, the helper function:

Next, let’s say that the request that’s being made contains invalid data. To handle this, you’d use the above helper like the following:

On the flipside, let’s say everything works fine:

As you can see, this function uses native WordPress hooks, facilities of PHP, and also creates a method that can be unit tested which matters if you’re aiming to write testable web applications in WordPress.

And even if not, you’ve got an easier way to keep your code a bit more DRY than it was before.