The doing_filter()
WordPress PHP function allows you to determine if a filter hook is currently being processed. It’s handy for detecting any filter that’s currently executing, even if it’s not the most recent one. In addition, it can verify the number of times a filter has been applied during the current request.
Usage
Here’s a simple example of how to use doing_filter()
. This code will print “A filter is being processed!” if any filter is currently in operation:
if (doing_filter()) { echo "A filter is being processed!"; }
And here’s an example where we check if a specific filter named ‘posts_results’ is being processed:
if (doing_filter('posts_results')) { echo "The 'posts_results' filter is being processed!"; }
Parameters
$hook_name string|null
(optional): The name of the filter hook to check. If set to null (default), the function will check if any filter is currently being run.
More information
See WordPress Developer Resources: doing_filter()
This function is part of the WordPress Core and can be used in themes, plugins, and other areas where you need to check the state of a filter hook.
Examples
Checking if any filter is running
This code will print a message if any filter is being processed.
if (doing_filter()) { echo "Some filter is currently being processed!"; }
Checking a specific filter
This code will check if the ‘posts_results’ filter is being processed.
if (doing_filter('posts_results')) { echo "The 'posts_results' filter is currently being processed!"; }
Taking action if no filters are running
This code will run a function run_my_function()
only if no filters are being processed.
if (!doing_filter()) { run_my_function(); }
Checking multiple filters
This code checks if either ‘posts_results’ or ‘pre_get_posts’ filters are currently being processed.
if (doing_filter('posts_results') || doing_filter('pre_get_posts')) { echo "Either 'posts_results' or 'pre_get_posts' filter is being processed!"; }
Preventing a function run during a specific filter
This code prevents run_my_function()
from executing if the ‘posts_results’ filter is being processed.
if (!doing_filter('posts_results')) { run_my_function(); }