Using WordPress ‘did_action()’ PHP function

The did_action() WordPress PHP function retrieves the number of times an action has been fired during the current request.

Usage

Here’s an example of how to use the function. Let’s say we have an action hook named ‘my_action’ and we want to know how many times it has been fired.

$times_fired = did_action('my_action');
echo $times_fired;

If ‘my_action’ has been fired twice during the current request, the output will be 2.

Parameters

  • $hook_name (string) – The name of the action hook.

More information

See WordPress Developer Resources: did_action()
It’s important to note that this function is not deprecated and is included in all WordPress versions.

Examples

Checking if an action has been fired at least once

Let’s say we want to check if an action named ‘init’ has been fired at least once. This can be done as follows:

if (did_action('init')) {
    echo 'The "init" action has been fired at least once.';
}

Limiting a function to run only once per request

We can use did_action() to make sure a function only runs once per request.

function run_once_per_request() {
    if (did_action('my_custom_action') === 0) {
        do_action('my_custom_action');
        // Function code goes here...
    }
}

Counting the number of times a custom action has been fired

This code snippet will count the number of times a custom action named ‘my_custom_action’ has been fired.

$times_fired = did_action('my_custom_action');
echo "The 'my_custom_action' has been fired " . $times_fired . " times.";

Conditional action based on the number of times an action has been fired

This example shows how to perform a conditional action based on the number of times an action has been fired.

$times_fired = did_action('my_custom_action');
if ($times_fired > 5) {
    echo 'The "my_custom_action" action has been fired more than 5 times.';
} else {
    echo 'The "my_custom_action" action has not been fired more than 5 times yet.';
}

Adding a custom meta field during the first run of an action

This example adds a custom meta field during the first run of the ‘quick_edit_custom_box’ action.

function my_sticky_option() {
    global $post;
    if ($post->post_type == 'custom_post_type' && did_action('quick_edit_custom_box') === 1) {
        // Your HTML code for the custom meta field goes here...
    }
}
add_action('quick_edit_custom_box', 'my_sticky_option');

In this code, did_action() is used to check if the ‘quick_edit_custom_box’ action has been fired once. If it has, a custom meta field is added. This ensures that the custom meta field is only added once, during the first run of the ‘quick_edit_custom_box’ action.