Difference between add_filter and apply_filters

Most of the following can be found in the Codex:


apply_filters

The callback functions attached to filter hook $tag are invoked by calling this function. This function can be used to create a new filter hook by simply calling this function with the name of the new hook specified using the $tag parameter.

$value = apply_filters( $tag, $value, $var_1, $var_2, ... );

In essence:
You use apply_filters to filter a given $value – with respect to the value itself as well as optionally provided variables $var_1 through $var_n.


add_filter

Hook a function to a specific filter action.

add_filter( $tag, $function_to_add, $priority, $accepted_args );

In essence:
You use add_filter to hook a custom function to the given filter action ($tag), which you might have generated by apply_filters before (or it was a built-in filter action or stems from a plugin/your theme).


So, here’s a fictional example:

function print_initials( $name ) {

    if ( ! is_string( $name ) ) {
        return;
    }

    $fragments = explode( ' ', $name );

    /**
     * Filter wether to print initials in reverse order.
     *
     * @param bool $reverse Print initials in reverse order?
     */
    if ( apply_filters( 'reverse_initials', FALSE ) ) {
        $fragments = array_reverse( $fragments );
    }

    foreach ( $fragments as $f ) {
        echo substr( $f, 0, 1 );
    }
}

print_initials( 'Some Guy' ); // outputs: SG

add_filter( 'reverse_initials', '__return_true' );

print_initials( 'Some Guy' ); // outputs: GS

Now, if we just call our function as is, the initials 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 initials be output from right to left.

Leave a Comment