Using WordPress ‘has_filter()’ PHP function

The has_filter() WordPress PHP function checks if any filter has been registered for a hook.

Usage

$result = has_filter('hook_name', 'callback_function');

Parameters

  • $hook_name (string): The name of the filter hook.
  • $callback (callable|string|array|false, optional): The callback to check for. Default: false.

More information

See WordPress Developer Resources: has_filter()

Examples

Check if a filter is registered for a specific hook

This code checks if there’s any filter registered for the ‘the_content’ hook.

if (has_filter('the_content')) {
    echo 'A filter is registered for the_content hook.';
}

Check if a specific callback is registered for a hook

This code checks if the ‘example_alter_the_content’ callback is registered for the ‘the_content’ hook.

if (has_filter('the_content', 'example_alter_the_content')) {
    echo 'example_alter_the_content is registered for the_content hook.';
}

Register a filter only if it’s not already registered

This code registers ‘prefix_alter_the_content’ filter for ‘the_content’ hook if it’s not already registered.

if (!has_filter('the_content', 'prefix_alter_the_content')) {
    add_filter('the_content', 'prefix_alter_the_content');
}

Remove a filter if it’s registered

This code removes the ‘example_alter_the_content’ filter from the ‘the_content’ hook if it’s registered.

if (has_filter('the_content', 'example_alter_the_content')) {
    remove_filter('the_content', 'example_alter_the_content');
}

Check if a filter with a class method is registered

This code checks if the ‘alter_the_content’ method of the ‘Example_Class’ class is registered for the ‘the_content’ hook.

if (has_filter('the_content', array('Example_Class', 'alter_the_content'))) {
    echo 'Example_Class::alter_the_content is registered for the_content hook.';
}