current_filter()
云策文档标注
概述
current_filter() 函数用于检索当前正在执行的 filter hook 的名称。它返回当前 filter 的 hook 名称,如果没有 filter 在运行则返回 false。
关键要点
- 函数返回当前 filter hook 的名称,类型为字符串或 false。
- 内部实现基于全局变量 $wp_current_filter,通过 end() 函数获取数组最后一个元素。
- 可用于在 filter 回调中识别当前触发的 hook,例如在 add_filter() 或 add_action() 中。
代码示例
function wpdocs_my_filter() {
echo current_filter(); // 'the_content'
}
add_filter( 'the_content', 'wpdocs_my_filter' );注意事项
- 该函数自 WordPress 2.5.0 版本引入。
- 与 current_action() 类似,但 current_filter() 专门用于 filter hooks。
- 在 action hooks 中调用时,也会返回当前 action 的名称,因为 actions 是 filters 的一种特殊类型。
原文内容
Retrieves the name of the current filter hook.
Source
function current_filter() {
global $wp_current_filter;
return end( $wp_current_filter );
}
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |
Skip to note 3 content
Codex
Get the current filter
function wpdocs_my_filter() { echo current_filter(); // 'the_content' } add_filter( 'the_content', 'wpdocs_my_filter' );Skip to note 4 content
Codex
Get the current action
function wpdocs_my_init_function() { echo current_filter(); // 'init' } add_action( 'init', 'wpdocs_my_init_function' );