Here is a quick WordPress developer tip.
Sometimes we need to remove an already declared action or filter in a plugin or theme.
It’s pretty easy to do this in functional programming using remove_action() and remove_filter().
Here are some examples:
Removing these types of actions and filters is easy:
Removing actions and filters gets a bit more complex when they are declared inside a PHP Class.
Let us look at a simple plugin class that registers an action hook:
The action hook (and filters) are registered in an array that binds to the current class using $this.
How do you replicate that to remove the hook or filter?
Removing Action Hooks and Filters In a Class
When removing action hooks and filters, remember to use the exact same creation parameters.
For the example above, you need to use the class object to remove the hook.
There are two ways to achieve this.
Using the Class Object Instance
The last line highlighted in the code above shows the class object instance saved to the variable $blue_widgets.
For defined objects in a variable, you can use it to remove the hook or filter. Example:
When dealing with static classes with no instantiation, you need to use the following method.
Removing Hooks and Filters When a Class Does Not Have an Instance
In this case, we need to use the class name itself to remove hooks and filters.
Matching the Priority and Arguments Parameters
The functions add_action() and add_filter() have an additional two optional parameters int $priority = 10, int $accepted_args = 1.
These parameters determine the priority (defaults to 10) and the number of accepted arguments (defaults to 1).
When removing an action hook or filter, you must also match the priority parameter.
Let’s look at the previous code block with those two parameters added to see how we can remove it later.
In the example above, line 4 has been modified to add a priority of “12” and a function parameter “true”.
To remove the action, match you must also include the matching priority parameter.
Hopefully, you find this developer tip useful in your plugins and themes.