Saturday 21 November 2015

How to Add and Remove Your Own Functions

If you would like to hook in your own functions, the process is quite simple. You first need to know a few pieces of information. For actions, you’ll want to know the name of the hook, as well as when exactly it runs.
For filters, you also need to know the name of the hook, but you want to know what value you are going to get and have to return, as well. The final bit of information you need is the name of the function where you have all your code.
How to Hook into an Action
add_action( $hook, $function_to_add, $priority, $accepted_args );
The required parameters of the add_action function are the hook and function to add. The priority is an optional integer value based on a scale of 1 to 999 that determines the priority of order for functions tied to that specific hook. Higher priority means it runs later, lower priority means earlier. The last parameter is used less often and it is for when you need to pass or accept multiple arguments.
How to Hook into an Filter
add_filter( $tag, $function_to_add, $priority, $accepted_args );
The add_filter works the same way as add_action. You will also have to be careful because sometimes a hook exists as both an action and a filter, or a filter and a function. You will see the real difference with the actual function you call.
Remember that, for a filter, the function_to_add both receives a value and has to return it at the end of the function. Actions, on the other hand, simply run the code they need to and don’t return a value.
How to Unhook from Actions and Filters
To remove a hook is quite simple. Use the function remove_action or remove_filter along with the name of the hook, function, and priority. The priority is optional and helpful if you have to unhook a function that is hooked more than once and you only want to remove a specific occurrence of that function.
remove_action( $tag, $function_to_remove, $priority );
remove_filter( $tag, $function_to_remove, $priority );
Now that we have looked at the basics of how functions are hooked and unhooked, let’s take a look at a few real world examples of some different hooks in action.

No comments:

Post a Comment

Popular Articles