How to pass a parameter to this add_filter example [duplicate]

The trick Toscho used was to get around the problem using Objects.

So lets say we have a filter named xyz, that passes in some post content. The goal of this hypothetical scenario is to append a word to the content that we can not “hardcode”.

Here’s the basic filter:

add_filter( 'xyz', 'test' );
function test( $content ) {
    return $content;
}

So we append to $content, but how do we get the value to append? That is the crux of your issue.

To solve this problem you can use OOP:

class test_object {
    public $appended_value="";
    function test( $content ) {
        return $content.$this->appended_value;
    }
}

$obj = new test_object();
$obj->appended_value="hello world";
add_filter( 'xyz', array( $obj, 'test' ) );

Here the class/object is being used to store the extra data.

An alternative to this would be to use a closure ( not a lambda function ) to create a new function based on a value, but this will not work prior to PHP 5.3, e.g.:

add_filter('xyz', 
    function($content) use ($appended_value) {
        return $content.$appended_value;
    }
);

Disclaimer: None of this code is copy paste, it is for demonstrative purposes.

Leave a Comment