How Can I Add a Filter to Class Instance Only?

The problem is that filters in WordPress are global; if you add a filter somewhere it persists everywhere, unless you remove it.

Also consider that you should prefer composition over inheritance, and if your current application structure is already built upon inheritance, and you can’t or don’t want to change it, you should avoid at least using filters for things that aren’t global.

By separating the logic that returns data from the logic that filters it, everything becomes much easier:

class A {

    function get_things() {
        return array( 'coffee', 'tea' );
    }

    function show_things() {
        return apply_filter( 'yet_another_filter', $this->get_things() );
    }

}

class B extends A {

    function get_things() {
        return array( 'crisps', 'beer' );
    }

}

class C extends A {

}

As you can guess:

$a = new A;
$b = new B;
$c = new C;

$a->show_things(); // array( 'coffee', 'tea'  )
$b->show_things(); // array( 'crisps', 'beer'  )
$c->show_things(); // array( 'coffee', 'tea'  )

All the results pass through "yet_another_filter" filter, allowing external code to overwrite results in all cases, which is what a filter is intended for.

Leave a Comment