WordPress allows developers to filter the output using apply_filters. You might be using it to alter the output without changing the original value.
This makes it easy for plugin and theme authors to apply various filters and alter the output. However, it gets complicated when there are multiple filters applied for the same output.
It was not possible to check if your filter had been run or not in older versions of WordPress. With WordPress 6.1, the new function did_filter solves this problem. This function returns the number of times the filter has been applied in the current request.
How to Use the did_filter Function
If you are familiar with did_action, then this is easy to guess. The did_action function allows you to check if an action has been fired in the current request.
if( did_action( 'hook_name' ) ){ // do something }
The did_filter function works the same way, but it checks for the filter. Let’s take a look at this simple implementation
For this example, let’s imagine a scenario where we want to append the category name to the post title using a filter. And if the category name is already appended, the callback should stop the execution.
- plugin_title_change prepends the category name to the post’s title by using the filter ‘lax_plugin’
- theme_title_change plugin checks if the lax_plugin filter is already executed, then prepends the category name
This prevents the duplicate execution of the filter.
How Does It Work?
Every time when we use apply_filters, the global variable $wp_filters gets incremented. See this snippet from the core apply_filters function.
if ( ! isset( $wp_filters[ $hook_name ] ) ) { $wp_filters[ $hook_name ] = 1; } else { ++$wp_filters[ $hook_name ]; }
did_filter just returns the count of the hook from the global $wp_filters array.
function did_filter( $hook_name ) { global $wp_filters; if ( ! isset( $wp_filters[ $hook_name ] ) ) { return 0; } return $wp_filters[ $hook_name ]; }
When to Use the did_filter Function
The most common use case is to check whether a filter has been applied. You can also use this function to check the number of times a filter has been applied during the current request.
Side note: At the time of this writing, VS code extension PHP Intelephense v1.9.4, throws a warning “Undefined function ‘did_filter’.intelephense(1010).” You can safely ignore it, and the function should work as expected.