How To Determine Current Action Name and Priority
Editorial Note We may earn a commission when you visit links from this website.

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“?

Table of Contents

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 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:

<?php

/**
 * Output the current action name and priority.
 */
function pst_action_and_priority() {
 global $wp_filter, $wp_current_filter;

 // Find the currently running WP action/filter name.
 $action = end( $wp_current_filter );
    
 // Get the corresponding WP_Hook object of that filter.
 $filter = $wp_filter[ $action ];
  
 // Determine the priority of the current filter callback.
 $prio = $filter->current_priority();
    
 echo "Action $action [Prio $prio]\n";
}

add_action( 'login_init', 'pst_action_and_priority' );
add_action( 'login_form', 'pst_action_and_priority' );
add_action( 'login_form', 'pst_action_and_priority', 1 );
add_action( 'login_form', 'pst_action_and_priority', 100 );

/*
Output:

Action login_init [Prio 10]
Action login_form [Prio 1]
Action login_form [Prio 10]
Action login_form [Prio 100]
*/

Try Divi Areas Pro today

Sounds interesting? Learn more about Divi Areas Pro and download your copy now!
Many pre-designed layouts. Automated triggers. No coding.

Click here for more details