did_action()
Retrieve the number of times an action (hook) is fired.
The function returns the number of times an action is fired, not the number of functions attached to an action. I.e. it counts do_action(), not add_action().
Similiar functions:
- current_filter() — retrieve the name of the current filter or action.
- current_action() — alias (copy) of current_filter().
- doing_filter() — check whether the specified hook is currently being processed.
- doing_action() — alias (copy) of doing_filter().
Does not work with filters, in WP 6.1 a new function did_filter()
appeared.
1 time — 0.0000001 sec (speed of light) | 50000 times — 0.0001 sec (speed of light) | PHP 7.4.8, WP 5.7
No Hooks.
Return
Int
. The number of times the action hook has been fired.
Usage
did_action( $hook_name );
- $hook_name(string) (required)
- The name of the action hook.
Examples
#1 Basic example
// this line does not affect the result `did_action()` add_action( 'hook_name', '__return_true' ); echo did_action( 'hook_name' ); //> 0 do_action('hook_name'); // first call echo did_action( 'hook_name' ); //> 1 do_action('hook_name'); // second call echo did_action( 'hook_name' ); //> 2
#2 Do something if the specified hook has never worked
if( did_action('hook_name') === 0 ){ // hook 'hook_name' has never worked ... }
#3 Do something if the specified hook has worked only once
did_action() can be used to do something only 1 time, when the hook fires the first time.
Let's use did_action() to make sure that an custom field was added only during the first event call. All subsequent calls of the action function will do nothing:
<?php function my_sticky_option(){ global $post; if ( $post->post_type == 'films' && did_action( 'quick_edit_custom_box' ) === 1 ){ ?> <fieldset class="inline-edit-col-right"> <div class="inline-edit-col"> <label class="alignleft"> <input type="checkbox" name="sticky" value="sticky" /> <span class="checkbox-title"> <?php _e( 'Featured (sticky)', 'textdomain_string' ); ?> </span> </label> </div> </fieldset> <?php } } // add a sticky setting to the quick edit box add_action( 'quick_edit_custom_box', 'my_sticky_option' );
Notes
- Global. Int[]. $wp_actions Stores the number of times each action was triggered.
Changelog
Since 2.1.0 | Introduced. |
did_action() did action code WP 6.6.2
function did_action( $hook_name ) { global $wp_actions; if ( ! isset( $wp_actions[ $hook_name ] ) ) { return 0; } return $wp_actions[ $hook_name ]; }