[PHP] 3 MUST know things about WordPress Hook/Filter
I am working on the work of Plugin and Theme development, that requires so much work on customizing the admin dashboard, theme and the database. That is a chance to understand the Zen of wordpress — Action Hook .
Hook/Action is a powerful main course of WordPress, which helps to provide great flexibility when customizing WordPress, because 2000+ hooks have been prepared for developers to use during the design of the wordpress system.
The Hook processing method is actually very simple. When PHP Wordpress prepares the HTMl text data, it has its own execution order, so the author has inserted 2000+ hooks “holes” to allow developers to modify the page in the desired “holes”. Or perform an action.
So you can quickly modify custom themes and plug-ins. In this quick article, I will give you a simple example to demonstrate the role of filter hooks.
When using the filter Filter, you will often use four main core functions:
- add_filter()-used to add a new custom filter
- remove_filter()-used to delete the registered filter
- apply_filters() — run the provided data through the specified filters
- has_filter() — check if a specific filter has been registered
1) add_action & add_filter are originally from the same root
Even if you look the core of WordPress, you will find that there is not much difference between actions and filters. Here is the source code for the ADD_ACTION() function from the wp-includes/plugin.php file:
The add_action() function just calls the add_filter() function and returns its value. Why? Because they fundamentally work in the same way, except for one difference.
The apply_filters() function returns a value that can change the existing data type, while the do_action() function returns nothing (NULL value in PHP).
2) 3 MUST know things of WordPress Hook/Filter, naming, parameters, callback
The following are the actions that need to be announced/registered to actually use the action/filter function. The three parts hooks, hook functions, and callback function are used to control the relationship between
- hook naming (action_name / filter_name)
- parameters
- callback
3) Where to register the hook and its function?
There are two recommended ways to add hooks in WordPress:
Plugin: Make your own plug-in and add all custom codes in it.
Theme: Register hooks and callback functions in the functions.php file of the child theme.
Reference:
- https://developer.wordpress.org/reference/functions/add_filter/
— All 2000+ hook: https://adambrown.info/p/wp_hooks/version/5.7
— https://kinsta.com/blog/wordpress-hooks/
— https://learnwoo.com/what-are-wordpress-hooks/