函数文档

has_filter()

💡 云策文档标注

概述

has_filter() 函数用于检查指定的过滤器钩子是否已注册任何回调函数。它支持检查钩子是否有任何注册,或特定回调函数是否已附加,并可指定优先级进行验证。

关键要点

  • 函数签名:has_filter( $hook_name, $callback = false, $priority = false ),返回 bool 或 int 类型值。
  • 当省略 $callback 时,返回布尔值表示钩子是否有任何注册;提供 $callback 时,返回该回调的优先级或 false(如果未附加)。
  • 如果同时提供 $callback 和 $priority,返回布尔值表示特定回调是否在指定优先级注册。
  • 注意:使用 $callback 参数时,返回值可能为非布尔假值(如 0),建议用 === 运算符测试返回值。
  • 相关函数:has_action() 用于检查动作钩子。

代码示例

// 检查钩子是否有任何注册
if ( has_filter( 'the_content' ) ) {
    // 执行操作
}

// 检查特定回调是否注册
$priority = has_filter( 'the_content', 'my_callback_function' );
if ( $priority !== false ) {
    echo "回调已注册,优先级为:$priority";
}

// 检查回调是否在特定优先级注册
if ( has_filter( 'the_content', 'my_callback_function', 10 ) ) {
    // 回调在优先级 10 注册
}

注意事项

在性能方面,直接调用 add_filter() 可能比先用 has_filter() 检查再添加更快;has_filter() 更适合检查钩子是否有任何注册,而非避免重复注册特定回调。


📄 原文内容

Checks if any filter has been registered for a hook.

Description

When using the $callback argument, this function may return a non-boolean value that evaluates to false (e.g. 0), so use the === operator for testing the return value.

Parameters

$hook_namestringrequired
The name of the filter hook.
$callbackcallable|string|array|falseoptional
The callback to check for.
This function can be called unconditionally to speculatively check a callback that may or may not exist.

Default:false

$priorityint|falseoptional
The specific priority at which to check for the callback.

Default:false

Return

bool|int If $callback is omitted, returns boolean for whether the hook has anything registered. When checking a specific function, the priority of that hook is returned, or false if the function is not attached.
If $callback and $priority are both provided, a boolean is returned for whether the specific function is registered at that priority.

Source

function has_filter( $hook_name, $callback = false, $priority = false ) {
	global $wp_filter;

	if ( ! isset( $wp_filter[ $hook_name ] ) ) {
		return false;
	}

	return $wp_filter[ $hook_name ]->has_filter( $hook_name, $callback, $priority );
}

Changelog

Version Description
6.9.0 Added the $priority parameter.
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    add_filter() calls the same _wp_filter_build_unique_id() function and re-assigns the method/function parameter to the index array.

    It is very likely that calling add_filter() with the same parameter list is faster than first checking if the method/function is already registered with has_filter( , ) before adding it with add_filter( , );

    I am guessing the best use-case for has_filter() is to check if a filter has ANY registered methods versus checking that a specific method exists prior to re-registering it with add_filter() .