Introduction
add_filter()
and apply_filters()
are two WordPress function which are often difficult to understand how these two functions work together. In this blog post, how to use add_filter()
and apply_filters()
effectively.
How apply_filter works?
Most updated information about using WordPress functions can be found on the Codex:
apply_filters( $tag, $value, $var_1, $var_2, ... );
Parameters
- $hook_name
-
(string) (Required) The name of the filter hook.
- $value
-
(mixed) (Required) The value to filter.
- $args
-
(mixed) (Required) Additional parameters to pass to the callback functions.
Return
(mixed) The filtered value after all hooked functions are applied to it.
How add_filter works?
Hook a function to a specific filter action.
add_filter( $tag, $function_to_add, $priority, $accepted_args );
WordPress offers filter hooks to allow plugins to modify various types of internal data at runtime.
A plugin can modify data by binding a callback to a filter hook. When the filter is later applied, each bound callback is run in order of priority, and given the opportunity to modify a value by returning a new value.
function print_username( $name ) {
if ( ! is_string( $name ) ) {
return;
}
$fragments = explode( ' ', $name );
/**
* Filter wether to print username in reverse order.
*
* @param bool $reverse Print username in reverse order?
*/
if ( apply_filters( 'alter_username', FALSE ) ) {
$fragments = array_reverse( $fragments );
}
foreach ( $fragments as $f ) {
echo substr( $f, 0, 1 );
}
}
print_username( 'Some Guy' );
// outputs: SG
add_filter( 'alter_username', '__return_true' );
print_username( 'Some Guy' );
// outputs: GS
Now, if we just call our function as is, the username are printed from left to right—because this is what we defined as default behavior.
The second time, we get the initials in reverse order—because the filter function __return_true
, which is hooked to our filter action, always returns TRUE
and thus makes the username be output from right to left.