Join Carrie Dils for an in-depth discussion in this video Adding custom hooks, part of Advanced WordPress: Action and Filter Hooks.
- [Narrator] We've looked at various hooks that WordPress provides and we know that these are part of the plugin API that enable us to inject our own code into WordPress. If you're writing a plugin, you may choose to give other developers a way to interact with your code, and you could do that by creating your own hooks. Creating your own hooks is actually pretty easy. We use apply filters to create a filter hook, and do action to create an action hook. Let's take a look at an example. Let's say that you've got a plugin, it's called Your Plugin, you've got a function called top, and in it you return the string and then echo it, saying this is the top, and then a very similar function down at the bottom.
Now, what if I had a plugin and I wanted to interact with your plugin? Well the way your plugin is currently written, I don't have any way to do that. So this is where creating your own hook would come into play. So let's say that you create a hook in your plugin called in the middle. Then when I go to write my plugin, I can call in the middle and attach my own function to your hook, and in that case, I could echo something and say, this is in the middle.
So by creating a custom hook here, in your code, I'm able to interact with it in my plugin. Now how about a filter? Let's say that I wanted to be able to filter that text for the top function that says, this is the top. Well, currently, I can't interact with your code in that way. You've created a filter for top text that I can then add in my plugin to change the output of that top function. Pretty cool. So creating your own action and filter hooks is pretty straight forward.
Now, depending on what sort of plugin you're writing, and who you're writing for, you may opt to include your own custom hooks. I'd encourage you, though, to be very intentional about when you do, because once you've added a hook, if another developer out there has used it, you can't ever take it back if you want to maintain backwards compatibility. A good rule of thumb to use when deciding on whether or not to add a hook to your code is whether or not another developer has asked for it. If they haven't, you may want to hold off.
- Actions and filters explained
- Identifying available hooks and filters
- Looking at load order
- Understanding callback functions
- Creating custom hooks
- Using third-party hooks
- Building a new WordPress plugin with filters and actions