When does remove_filter not work?

There are reports that remove_filter does not work under some circumstances, and that we should provide alternatives. However, the article does not really make it clear under which circumstances this happens.

I am looking for code examples that will break remove_filter, with WordPress and PHP version, and eventually other relevant info, provided. I think the following snippet should be a useable template:

Read More
<?php
include('wp-load.php');

function filtertest_function($value)
{
    return 'Filtered';
}

var_dump(apply_filters('filtertest', 'Original value'));
add_filter('filtertest', 'filtertest_function');
var_dump(apply_filters('filtertest', 'Original value'));
remove_filter('filtertest', 'filtertest_function');
var_dump(apply_filters('filtertest', 'Original value'));

This will return the expected:

string(14) "Original value"
string(8) "Filtered"
string(14) "Original value"

I believe the error comes up in some cases where the filter is part of a class, or multiple filters are used. I understand _wp_filter_build_unique_id is involved. Please point out where in that code the source of the error is.

Related posts

Leave a Reply

2 comments

  1. Well this is somehow a very specific topic that is bound to a WordPress development issue. I strongly suggest you to keep track of the trac ticket if you liked my article. That is the best thing you can do I assume for finding out when the problems come into play as well how to circumvent them technically (if you don’t like the don’t use remove_filter()-answer).

    Take it from a theoretic standpoint: It’s just that the used datatypes are not strictly dealt with to ensure the same functionality on all possible values (f(n) != f(n)). In short: a broken design.

    Does this mean it will always break in practise? – No! It’s just that it can happen sometimes. And then you’re trapped when you need to rely on remove_filter().

    A better suggestion might be this one: If you develop plugins that make use of hooks as class methods, ensure that the plugin get executed on installations with PHP 5.2 / 5.3.

    Please keep the technical discussion in the trac ticket. And if you’re seriously interested, please help to fix the shortcomings of the current design.

  2. As Denis commented on Hakre’s blog, this is a very basic example of the issue.

    function run_me_once() {
        remove_action( 'foobar', 'run_me_once' );
        echo 'test....';
    }
    add_action( 'foobar', 'run_me_once' );
    
    function run_me2() {
        echo 'test2....';
    }
    add_action( 'foobar', 'run_me2', 11 );
    
    echo '';
    do_action( 'foobar' ); // test....
    echo '';
    echo '';
    do_action( 'foobar' ); // test2....
    echo '';
    

    Before running that code though, ask yourself, what would you expect the result to be. Once you’ve decided what the result should be, run it and see what happens.