doing_filter()
云策文档标注
概述
doing_filter() 函数用于检测指定的或任意的过滤器钩子是否正在执行中。它通过检查全局变量 $wp_current_filter 来实现,帮助开发者判断当前请求中特定过滤器的执行状态。
关键要点
- 函数返回布尔值,指示过滤器是否在当前执行栈中。
- 参数 $hook_name 可选,默认为 null,表示检查是否有任何过滤器正在运行。
- 与 current_filter() 和 did_filter() 相关,但功能不同:current_filter() 返回最近执行的过滤器,did_filter() 返回过滤器被调用的次数。
- 可用于在过滤器回调中检测嵌套钩子的执行情况。
代码示例
// 检查是否有任何过滤器正在运行
if ( doing_filter() ) {
// 执行相关操作
}
// 检查特定过滤器 'posts_results' 是否正在运行
if ( doing_filter( 'posts_results' ) ) {
// 执行相关操作
}注意事项
- 函数自 WordPress 3.9.0 版本引入。
- 在插件或主题开发中,常用于条件逻辑,以避免在特定过滤器执行时重复操作或冲突。
- 注意与 doing_action() 区分,后者用于动作钩子。
原文内容
Returns whether or not a filter hook is currently being processed.
Description
The function current_filter() only returns the most recent filter being executed.
did_filter() returns the number of times a filter has been applied during the current request.
This function allows detection for any filter currently being executed (regardless of whether it’s the most recent filter to fire, in the case of hooks called from hook callbacks) to be verified.
See also
Parameters
$hook_namestring|nulloptional-
Filter hook to check. Defaults to null, which checks if any filter is currently being run.
Default:
null
Source
function doing_filter( $hook_name = null ) {
global $wp_current_filter;
if ( null === $hook_name ) {
return ! empty( $wp_current_filter );
}
return in_array( $hook_name, $wp_current_filter, true );
}
Changelog
| Version | Description |
|---|---|
| 3.9.0 | Introduced. |
Skip to note 3 content
Codex
To check if any filter is being applied you could write something like this:
if (doing_filter() ) { // Do Something Here }Skip to note 4 content
Akira Tachibana
(From Codex)
To check whether the ‘posts_results’ filter is being applied you could write something similar to this:
if ( doing_filter( 'posts_results' ) ) { //Do Something Here }