WordPress Tip: Use Closures for WP Actions and Filters

In this tutorial I will show you an alternative way to add functionality to action and filter hooks by using PHP closures, also called anonymous functions.

Normal way with global function

Normally we have to create a global function, for example “demo_plugin_show_notice”. Then we add this function to an action, in this case “admin_notices”.
When the action “admin_notices” is triggered by the WordPress Core, our function will be executed, which results in printing the notice on the screen.

function demo_plugin_show_notice()
{
    echo '<div class="notice notice-success">';
    echo '<p>Yeah, Demo Plugin is activated!</p>';
    echo '</div>';
}

add_action('admin_notices', 'demo_plugin_show_notice');

So in this classic approach we need to create a global function. And although it is conventional in procedural code to use global functions and global variables, like in the WordPress Core, it’s considered a bad practice in the object oriented way of programming (which is becoming more standard).

The Problem

Using globals could cause naming conflicts. And when functions share the same name, PHP will throw a fatal error. And this problem could be solved by using closures.

Solved by using closures

Closures or anonymous functions are functions without a name and can be stored in a variable or passed on as an argument to a function call.
Now we copy the global function and replace the second argument of the add_action with this function. We will remove the function name to make it anonymous. And we move the opening accolade to the previous line to make it more readable. Now the code should work just the same, but without polluting the global namespace.

add_action('admin_notices', function () {
    echo '<div class="notice notice-success">';
    echo '<p>Yeah, Demo Plugin is activated!</p>';
    echo '</div>';
});

Notice

A disadvantage of this solution is that it’s not possible to remove the function from the action or filter hook at a later point. But in most cases you don’t need to.

And that’s it!

Leave a Reply