Using WordPress ‘current_action()’ PHP function

The current_action() WordPress PHP function retrieves the name of the current action hook.

Usage

Here’s an example of how you might use this function:

$current_action = current_action();

if ($current_action == 'init') {
echo 'WordPress is initializing';
}

In this example, the function current_action() is called to get the name of the current action hook. If the current action is ‘init’, the message ‘WordPress is initializing’ will be output.

Parameters

  • This function does not accept any parameters.

More information

See WordPress Developer Resources: current_action()

This function is not deprecated and can be found in the WordPress core files, specifically in the plugin.php file.

Examples

Check if in ‘wp_head’ action

In this example, we check if the current action is ‘wp_head’.

$current_action = current_action();

if ($current_action == 'wp_head') {
echo 'We are in the wp_head action';
}

Here we check if the current action is ‘wp_footer’.

$current_action = current_action();

if ($current_action == 'wp_footer') {
echo 'We are in the wp_footer action';
}

Check if in ‘init’ action

This time, we check if the current action is ‘init’.

$current_action = current_action();

if ($current_action == 'init') {
echo 'WordPress is initializing';
}

Using in a switch statement

We can also use current_action() in a switch statement to perform different tasks based on the current action.

switch (current_action()) {
case 'init':
echo 'WordPress is initializing';
break;
case 'wp_head':
echo 'We are in the wp_head action';
break;
case 'wp_footer':
echo 'We are in the wp_footer action';
break;
default:
echo 'Unknown action';
}

Check if in ‘admin_init’ action

Lastly, we can check if the current action is ‘admin_init’, an action that fires as an admin screen or script is being initialized.

$current_action = current_action();

if ($current_action == 'admin_init') {
echo 'Admin area is initializing';
}