current_filter()WP 2.5.0

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.

Аналогичные функции:

1 time — 0.00001 sec (speed of light) | 50000 times — 0.01 sec (speed of light) | PHP 7.1.11, WP 4.9.5

No Hooks.

Returns

String|false. The name of the current filter or action.

Usage

$filter_name = current_filter();

Examples

0

#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 );
}
0

#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'
}
0

#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:

  1. apply_filters() calls my_filter_callback().
  2. Inside my_filter_callback() my_filter_callback_child() is called.
  3. my_filter_callback_child() echoes the result of current_filter().
  4. current_filter() returns the name of the currently executing filter — here it's 'my_filter'.

Notes

  • Global. String[]. $wp_current_filter Stores the list of current filters with the current one last

Changelog

Since 2.5.0 Introduced.

current_filter() code WP 7.0

function current_filter() {
	global $wp_current_filter;

	return end( $wp_current_filter );
}