Trouble understanding apply_filters()

In apply_filters()

apply_filters( $tag, $value, $var ... );

I’m having trouble wrapping my head around the $value and $var. I read the codex and it sounds like the $value can be modified, $var not, but I haven’t found any examples of this in the wild. It seems to be used as a way to pass a variable. In which case, what’s the difference between that and the $var?


Try to see the function with better names:

    $filter_name,     // used for add_filter( $filter_name, 'callback' );
    $value_to_change, // the only variable whose value you can change
    $context_1,       // context
    $context_2        // more context

So when that function is called as:

// wp-login.php line 94
apply_filters( 'login_body_class', $classes, $action );

You can use …

add_filter( 'login_body_class', 'function_to_change_login_body_class', 10, 2 );

… and get two variables passed to that function. You return the first, the second provides just more context:

function function_to_change_login_body_class( $classes, $action )
    if ( 'login' === $action )
        $classes[] = 'foo';

    if ( 'postpass' === $action )
        $classes[] = 'bar';

    return $classes;

The additional variables are there to make your decisions easier, not to change those too.

Leave a Comment