remove_action or remove_filter with external classes?

In a situation where a plugin has encapsulated its methods within a class and then registered a filter or action against one of those methods, how do you remove the action or the filter if you no longer have access to that class’ instance?

For example, suppose you have a plugin that does this:

class MyClass {
    function __construct() {
       add_action( "plugins_loaded", array( $this, 'my_action' ) );
    }

    function my_action() {
       // do stuff...
    }
}

new MyClass();

Noting that I now have no way of accessing the instance, how do I unregister the class? This: remove_action( "plugins_loaded", array( MyClass, 'my_action' ) ); doesn’t seem to be the right approach – at least, didn’t seem to work in my case.

8

The best thing to do here is to use a static class. The following code should be instructional:

class MyClass {
    function __construct() {
        add_action( 'wp_footer', array( $this, 'my_action' ) );
    }
    function my_action() {
        print '<h1>' . __class__ . ' - ' . __function__ . '</h1>';
    }
}
new MyClass();


class MyStaticClass {
    public static function init() {
        add_action( 'wp_footer', array( __class__, 'my_action' ) );
    }
    public static function my_action() {
        print '<h1>' . __class__ . ' - ' . __function__ . '</h1>';
    }
}
MyStaticClass::init();

function my_wp_footer() {
    print '<h1>my_wp_footer()</h1>';
}
add_action( 'wp_footer', 'my_wp_footer' );

function mfields_test_remove_actions() {
    remove_action( 'wp_footer', 'my_wp_footer' );
    remove_action( 'wp_footer', array( 'MyClass', 'my_action' ), 10 );
    remove_action( 'wp_footer', array( 'MyStaticClass', 'my_action' ), 10 );
}
add_action( 'wp_head', 'mfields_test_remove_actions' );

If you run this code from a plugin you should notice that the method of the StaticClass as well as the function will removed from wp_footer.

Leave a Comment