current_filter()
Gets the name of the current filter.
Intended for use inside a function attached to a filter, to dynamically get the name of the current filter from which the function is called.
Аналогичные функции:
- current_filter() — gets the name of the current action or filter.
- current_action() — copy of the function current_filter().
- doing_filter() — checks whether the specified hook is currently being processed.
- doing_action() — copy of the function doing_filter().
- did_action() — gets int of how many times the specified hook has fired.
- did_filter() — Since WP 6.1. Gets int of how many times the specified hook has fired.
No Hooks.
Returns
String|false. The name of the current filter or action.
Usage
$filter_name = current_filter();
Examples
#1 Dynamically changing the email header
An interesting example that shows how you can dynamically change the header of an email (who the email is from), depending on which filter the same function (filter_system_from_mail) is triggered from.
add_filter( 'wp_mail_from', 'filter_system_from_mail' );
add_filter( 'wp_mail_from_name', 'filter_system_from_mail' );
function filter_system_from_mail(){
$opt = 'wp_mail_from' == current_filter() ? 'admin_email' : 'blogname';
return get_option( $opt );
}
#2 Usage Example
Get the current filter name:
add_filter( 'the_content', 'wpdocs_my_filter' );
function wpdocs_my_filter() {
echo current_filter(); // 'the_content'
}
Get the current action name:
add_action( 'init', 'wpdocs_my_init_function' );
function wpdocs_my_init_function() {
echo current_filter(); // 'init'
} #3 Demo: get the name of the filter in which the function runs
In this example the mechanism of WordPress filters is demonstrated: the example illustrates that inside a callback you can determine which filter is currently executing using current_filter().
function my_filter_callback() {
my_filter_callback_child();
}
function my_filter_callback_child(){
echo current_filter();
}
add_filter( 'my_filter', 'my_filter_callback' );
apply_filters( 'my_filter', null ); //> my_filter
- add_filter( 'my_filter', 'my_filter_callback' ); — registers the function my_filter_callback as a handler for the my_filter filter.
- apply_filters( 'my_filter', null ); — runs the my_filter filter. WordPress calls all functions attached to it.
The call proceeds as follows:
- apply_filters() calls my_filter_callback().
- Inside my_filter_callback() my_filter_callback_child() is called.
- my_filter_callback_child() echoes the result of current_filter().
- current_filter() returns the name of the currently executing filter — here it's 'my_filter'.
Notes
- Global. String[].
$wp_current_filterStores the list of current filters with the current one last
Changelog
| Since 2.5.0 | Introduced. |
current_filter() current filter code WP 7.0
function current_filter() {
global $wp_current_filter;
return end( $wp_current_filter );
}