Remove a hook added within a PHP class in WordPress

Remove a hook added within a PHP 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 the 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

Bonus tip: priorities must match

Interesting thing is that if a priority parameter is used while adding an action, remove_action() call must have the same priority argument in order to remove the action properly. Take a look:

class Some_Plugin_Class {

  function __construct() {
    add_action( 'save_post', array( $this, 'my_action_callback' ), 57);
  }

  function my_action_callback(){
    //do something
  }

}

$some_plugin_class = new Some_Plugin_Class();

So, in this case, you should use the same “57” priority parameter on action removal:

global $some_plugin_class; //get access to the class object instance

remove_action('save_post', array($some_plugin_class, 'my_action_callback'), 57); //remove class hook using the same priority

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.