Seite auswählen

We all know how to attach a custom callback function to a WordPress action. It’s as simple as add_action( 'init', 'my_function' );

But what happens, when you have multiple actions run the same function? Take this code, as an example:

add_action( 'network_admin_notices', 'my_notices' );
add_action( 'user_admin_notices', 'my_notices' );
add_action( 'admin_notices', 'my_notices' );

This is useful when all notices are identical or very similar. But what to do, when we want to display a small difference in the “network_admin_notices“?

Some uncool options

We could copy-paste the entire function to make a small adjustment, but that’s not the kind of clean code we want to write.

Or we could split the code into two or three functions to separate identical output from action-specific output. But this often pollutes the global scope with a lot of functions or generates overly complex code that is hard to maintain.

This is why WordPress offers a way to identify the current action that calls the “my_notices” function! I admit it’s not too obvious on how to get the information…

The current_filter()

The simple core function current_filter() is a convenient way of finding out the current action name. It simply examines the global array $wp_current_filter and returns its last element.

How to find the priority

Though there is no core function for this (yet) you can quite easily find the action priority as well: Simply examine the two globals $wp_current_filter and $wp_filter, as the following code snippet shows: