Remove an action or a filter hook added within a class in WordPress

As many of you probably know, WordPress has an ability to remove actions and filters added via add_action() and add_filter() functions. This can be easily done with a simple call of remove_action() or remove_filter() function. Here is a quick usage example:

Let’s say that there is a plugin registering an action and a filter:

add_action('save_post', 'my_action_callback');
add_filter('the_content', 'my_filter_callback');

And you want to remove them via your theme (or a plugin), for any reason. You just use this:

remove_action('save_post', 'my_action_callback');
remove_filter('the_content', 'my_filter_callback');

That was easy, right? But the real problem may appear if action is registered in a plugin within its own class. Take a look at the example below:

class Some_Plugin_Class {
 
	function __construct() {
		add_action( 'save_post', array( $this, 'my_action_callback' ));
        }
 
        function my_action_callback(){
         //do something
        }
 
}
 
$some_plugin_class = new Some_Plugin_Class();

Using remove_action() if action hook is added within a class

Since action is registered within a class, you must use the class object in order to access its hooks. In the example below, there is an elegant way to remove the action hook.

global $some_plugin_class; //get access to the class object instance
 
remove_action('save_post', array($some_plugin_class, 'my_action_callback')); //remove class hook

Using remove_action() if class doesn’t have an instance

If a class doesn’t have an instance for any reason (i.e. a static class), use its name instead of an instance:

remove_action('save_post', array('Some_Plugin_Class', 'my_action_callback')); //remove static class hook

That’s it developers! Hope this one was helpful so feel free to leave us your thoughts in the comment section below.