While there is a did_action and did_filter to determine how often an action or a filter has been called, it works different then you might expect. Both work similar and only count whether do_action or apply_filters have been executed. They don’t check whether they have been actually used.

Since I needed such kind of check, how often the filter has been actually used by an add_action or add_filter, I came up with my own solution:

/**
 * Add check whether a filter has been executed.
 * \did_filter() of WordPress only counts the times \apply_filters() has been executed
 * and not the actual times it has been used by \add_filter().
 *
 * @param	string	$hook_name The name of the filter hook
 * @return	integer The number of times the filter hook has been run
 */
function my_did_filter( string $hook_name ): int {
	global $wp_filter;
	
	if ( ! isset( $wp_filter[ $hook_name ] ) || ! isset( $wp_filter[ $hook_name ]->callbacks ) ) {
		return 0;
	}
	
	return count( $wp_filter[ $hook_name ]->callbacks );
}
Code language: PHP (php)

If you just need a check whether or not an action or a filter have been used, there is a doing_action and doing_filter right within WordPress.

Leave a Reply

Your email address will not be published. Required fields are marked *