How does filters and hooks actually work in WordPress?
I'm asking about something advanced. How is it implemented in PHP? E.g how does it collect all the hooks from the different plugins and "attach" them to the core hooks etc.
Basically the "Plugin API," which summons Filters and Hooks, consists out of the following functions:
Overall there're a couple of globals (what else in WordPress world) involved:
The first one
So when an execute function is called, WordPress searches those globals arrays for the keys with that name. Then the attached callbacks get executed priority after priority. The only thing that happens up front are callbacks attached to the
When you add a callback using
Then it adds your callback to the
As you can see the main sub array is the
Later, when a filter gets called - happening with the
Hooks are included in both the WordPress core files and some parent themes files. They enable you to hook in content in a specific location in the file.
An example is the wp_head hook in WordPress. You can use this hook in your child theme to add content in that location'
Some premium themes also include action hooks which you can use in a child theme to do the same thing. Here's a visual map which includes all the the action hooks and the position they output your content in the Genesis theme framework.
Here's what the hook looks like if you opened the header.php file in the Genesis theme framework:
Here's a list of WordPress hooks you can use in many ways.
Filters enable you to modify the output of an existing function and is included in both the WordPress core files and some parent theme frameworks like Genesis.
Here's a list of the filters you can use with the Genesis Design Framework
Here's a list of the filters included in WordPress
Here's an example of how you can use a filter in a theme framework like Genesis:
The above code can be used in a child theme to modify the author says text in your comments. It works in any theme.
Here's another example which customizes the length of excerpts to 50 words:
You'll find the the_excerpt() function in the wp-includes/post-template.php file.
Here's what it looks like:
You can also use hooks and filters in plugins to do exactly the same thing and the code won't be lost when you update the parent theme or WordPress.
Basically, hooks and filters enable you to customize and modify both WordPress and your parent theme without editing the core WordPress files or your parent theme files.
Its significantly easier to customize a child theme when the parent theme framework includes hooks and filters because you never need to edit the parent themes template files. This way you can safely change themes as well.