Here is a quick WordPress developer tip.
WordPress is great for allowing developers to extend plugins and themes using action hooks and filters.
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 [codelet]remove_action()[/codelet] and [codelet]remove_filter()[/codelet].
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 [codelet]$this[/codelet].
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 [codelet]$blue_widgets[/codelet].
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 [codelet]add_action()[/codelet] and [codelet]add_filter()[/codelet] have an additional two optional parameters [codelet]int $priority = 10, int $accepted_args = 1[/codelet].
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.