apply_filters()
Applies the attached PHP function to the specified filter.
The PHP function is attached to the filter using add_filter().
Used where it is necessary to change the value of a variable (for example, to allow changing the original text).
Used in plugins and themes to create hook-filters (hooks that allow changing the original data).
New filters must have unique names and must not coincide with existing filter names in WP.
In addition to filters, WP also has actions; their principle of operation is the same. The only difference is that a filter must return the received variable, i.e., it filters (changes) the data, while an action allows triggering a function or doing something else at the moment this action occurs. Actions are triggered by the function do_action()
See also the similar function apply_filters_ref_array(), which allows passing parameters by reference.
No Hooks.
Returns
Mixed
. The filtered value $value
, which is passed to the hook handler function.
Usage
apply_filters( $hook_name, $value, ...$args );
- $hook_name(string) (required)
- The name of the filter.
- $value(string/array/number/object/boolean) (required)
- The value that will be passed to the function as its first argument, in other words - the value that needs to be filtered.
- ...$args(string/array/number/object/boolean)
- Additional values that the filter will pass to the function.
Examples
#1 Usage examples
Obtaining a filtered value:
$value = apply_filters( 'filter_name', $value );
Add filter function (this code need to be executed before apply_filters() call):
add_filter( 'filter_name', 'filter_function' ); function filter_function( $value ){ return $value; }
Filter value and display it:
echo apply_filters( 'filter_name', $value );
Pass Additional Arguments for filter function:
$value = apply_filters( 'filter_name', $value, $arg1, $arg2, ... );
For example:
$value = apply_filters( 'filter_name', 'filter me', 'arg1', 'arg2 ');
Add filter function with additional arguments:
add_filter( 'filter_name', 'filter_function', 10, 3 ); function filter_function( $value, $arg1, $arg2 ){ return $value; }
#2 Example of outputting formatted content posts through a filter.
Alternative to the_content() function:
global $post; echo apply_filters( 'the_content', $post->post_content );
Notes
- Global. WP_Hook[]. $wp_filter Stores all of the filters and actions.
- Global. Int[]. $wp_filters Stores the number of times each filter was triggered.
- Global. String[]. $wp_current_filter Stores the list of current filters with the current one last.
Changelog
Since 0.71 | Introduced. |
Since 6.0.0 | Formalized the existing and already documented ...$args parameter by adding it to the function signature. |