WordPress at a glance

did_action() WP 2.1.0

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:

✈ 1 time = 0.000013s = very fast | 50000 times = 0.01s = speed of light | PHP 7.0.5, WP 4.5.2

No Hooks.

Return

Int. The number of times action hook $tag is fired.

Usage

did_action( $tag );
$tag(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' );

Code of did action: wp-includes/plugin.php WP 5.2.2

<?php
function did_action( $tag ) {
	global $wp_actions;

	if ( ! isset( $wp_actions[ $tag ] ) ) {
		return 0;
	}

	return $wp_actions[ $tag ];
}

Related Functions

From tag: Actions (hooks)

More from category: Hooks (actions, filters)

No comments
    Hello, !     Log In . Register