Understanding and Using the WordPress Hook System
We’ve been covering quite a few WordPress web development topics recently, so you’ve probably already heard about hooks, actions, and filters.
These are an essential part of the using the event-driven architecture used by WordPress. And they are your path to creating your own custom “version” of WordPress to suit your needs.
- In a Nutshell
- Hooks, Actions or Filters? What’s What?
- The Difference Between Action Hooks and Filter Hooks
- Removing Filter and Action Hooks
- Enough with the Theory, Give Me Some WordPress Hook Examples!
- Where Else Can WordPress Hooks Be Used?
- Useful Hooks You Could Use
- WordPress Hooks: Your Imagination Is the Only Limit
In a Nutshell
An event-driven architecture is a way of listening for events that change a particular state and then reacting accordingly. Your reaction, what you write, is how you can create the functionality you desire to extend the functions of WordPress.
As a very simple example, publishing a WordPress post is an example of an event (
publish_post) which changes a state.
This is the foundation of the extensibility of WordPress, which has made the CMS such a rich ecosystem, thriving with thousands of feature-rich themes and plugins.
There is another fundamental reason why using WordPress hooks are critical.
Using hooks, you can extend and build upon WordPress without the need to edit any of the core source code.
Actually, let me rephrase that statement.
If anybody you hire for WordPress development (or work for) suggests a core change to the WordPress code, fire them on the spot.
Anybody, who is willing to break the upgradability of your WordPress website has no idea what they are talking about. If they had a grasp on the basics of security, they wouldn’t even think of doing that.
We’ve spoken about this before. Upgrading WordPress (and its themes and plugins) to the latest available version is one of the fundamentals of securing WordPress. Developers who change the core source code will leave your website a sitting duck.
If your hired developers are willing to take such a treacherous path, chances are they are not well-versed in the basics of coding either. It’s very likely they will wreak havoc with the code they write, leaving you (or the people you hire after them) to clean up the mess that they leave behind them.
On the other hand, if you use hooks and all of the other extensibility options WordPress gives you, the upgradability of your WordPress is assured.
That means, whenever a WordPress core update is released, upgrading your WordPress to the latest version won’t break any of your code. You don’t have to worry about the upgrade of your own custom development. As long as the hooks are not deprecated, your customizations will survive the upgrade.
More importantly, your WordPress is kept protected from any WordPress security vulnerability which has been secured through the latest WordPress core update.
Hooks, Actions or Filters? What’s What?
Hooks are basically events that happen during the execution of the functionality of WordPress, themes or plugins.
But why are they actually called hooks?
Developers who are looking to extend or implement specific functionality can “hook” onto the event as soon as it happens and perform a specific action related to that event.
As WordPress is going through its execution phases, it “checks” to see whether any plugin (or theme) has registered a function to be executed at that point, and if it finds any, those functions are executed at that point.
The WordPress codex, as part of the documentation of the WordPress API, explains Hooks, Actions and Filters quite nicely, but I’m supplementing this information of course.
There are two main types of hooks
- Actions (aka Action Hooks)
- Filters (aka Filter hooks)
In reality, these are quite similar in what they can achieve, but there are a few subtle differences.
The Difference Between Action Hooks and Filter Hooks
Let’s start with what’s the same before we discuss the differences.
Both actions and filter hooks receive data through a number of parameters.
Actions and filters are also mostly able to do the same thing (if you had to take a look at the WordPress source code, you’ll see that the code functions that implement actions are just wrappers of the filter code functions).
There is though, one key difference between the two types of WordPress hooks.
Filter hooks are required to return a value, action hooks do not.
In essence, with a filter hook, the hooked function gets a specific value, it does its thing and then returns that a modified (or not) version of that value.
An action hook does not need to return a value.
Putting it in more practical terms, with a filter hook, you’re typically working on content, doing your “changes” and then returning that content. For example, as we’ll see below the
title_save_pre filter hook works on the post title, whilst the
content_save_pre works on the content of the post.
On the other hand, an action hook does something (which can work on data or just use the data) when an event happens. The
publish_post action hook triggers when a post is published.
When and How to Use an Action Hook
You should use an action hook if you want to:
- Inject HTML or other content into the response buffer
- Modify one or more global variables
- Modify the parameters passed to your hook function
The way to add an action hook is as follows:
add_action( $hook, $function_to_add, $priority, $accepted_args );
$hook would be the action you want to hook onto, whilst
$function_to_add is the function you’ve written that will be executed when that hook is triggered.
We’ll see some real examples of doing this further on in this article.
When and How to Use a Filter Hook
You can use a filter when you need to do any of the above, but you also want / need to change the value of the data parameter.
In fact, it’s not just a want, it’s a requirement. You must return a value for the parameter if you are using a filter hook.
The way to adding a filter hook is quite similar to the way of adding an action hook:
add_filter( $hook, $function_to_add, $priority, $accepted_args );
Where once again,
$hook would be filter hook to use and
$function_to_add is the function you’ll be writing.
Removing Filter and Action Hooks
Removing WordPress hooks you’ve added is pretty simple. It’s the inverse of adding hooks and has a very similar syntax:
remove_action( $hook, $function_to_remove, $priority);
remove_filter( $hook, $function_to_remove, $priority);
$priority argument is an optional argument.
In both the
remove_filter case, the
$prioirity determines the order in which the hook triggers if there are several hooks “chained” or running one after the other on the same filter or action hook.
Enough with the Theory, Give Me Some WordPress Hook Examples!
Whilst I’ve mentioned that there are plenty of WordPress hooks you can use, I haven’t shown you exactly what they are so far.
Here is a list of all of the filter hooks you can use, courtesy of the WordPress Codex, whilst this is a list of all the action hooks. As you can see, the functionality within WordPress which you can hook onto is vast.
In fact, it’s unlikely you’ll come across a use-case for which a hook doesn’t exist.
And if you do come across such a use-case, you may want to contribute to WordPress and propose it’s inclusion in future versions of WordPress!
As at the time of writing, there are over 1900 hooks you can use.
Let’s see how we can hook onto them to do some simple additional functionality which is not available through the WordPress core.
Filter Hook Example #1
At the very beginning of this article, I mentioned that an example of a state change is the posting of a WordPress article.
For the sake of this example, what we’re going to do is create an attribution link at the bottom of each post, so that if anybody is reposting our articles on their website lock, stock and (two smoking) barrel(s), we’ll have, at the very least one backlink pointing back to our site.
For this reason, we’re going to hook onto the
content_save_pre filter hook, which is executed on the post content prior to saving it to the WordPress database.
As you can see, being a filter hook we’re changing, then returning, the content.
Filter Hook Example #2
Another pretty simple filter which is actually editing the output. Let’s say, for branding and SEO purposes, you want to append the name of your company to the titles in each WordPress post. Rather than using a SEO plugin, or asking your authors to do this manually, you can create a filter hook which does this as WordPress title is accessed.
As you can see, once again, our filter hook example is using
title_save_pre to do some changes to the title and then returning it.
Enough of filter examples, let’s go onto a few examples of action hooks. As you’ll see the primary differences with these is going to be that they won’t return any value.
Action Hook Example #1
You probably (should) know that pressing the Publish button on your post is the end of the publishing phase, but the actual beginning of the marketing phase. In terms of pushing out your content, you might want to start by pushing out the content to Social Networks as soon the post is published. At the very least, you may want to add them to you social media marketing schedule.
Now, if you want to semi-automate that process, you could hook onto the
publish_post action hook and post the content to your social media.
I won’t dig into the exact code for posting because this depends a lot on what you want to do exactly and there are plenty of tutorials on the interweb for that.
Action Hook Example #2
Let’s say you’ve created a membership plugin site. You’ve also created a number of bonus resources that you want to send as a separate email from the registration email.
What we will do is use the
after_signup_user action hook to send an additional email with the bonus content.
As can be seen, we are not actually returning any value (since this an action hook, not a filter hook).
The third argument of
add_action in the code above is the so-called hook priority that specifies the order in which the function hooked to the
after_signup_user action will be executed. The default (if not specific value) will be set to 10.
The fourth argument indicates the number of arguments the function hook will accept, which defaults to
1 if empty.
The Ubiquitous Code Example: Adding Google Analytics to WordPress Using an Action Hook
Just because this is one of the most prevalent examples online, doesn’t mean it isn’t a great example usage of actions hooks!
We’re hooking onto the
wp_head action hook to add our Google Analytics code.
Where Else Can WordPress Hooks Be Used?
Plugins and themes of course. Both core and custom WordPress plugins and themes will expose their own hooks for developers to be able to add their own custom functionality to the theme or plugin without breaking the theme or plugin.
As for the actual code, simple changes might go in the functions.php file, but there’s no actual specification or limit where the filters should go.
Useful Hooks You Could Use
If you’re convinced about the usefulness of hooks, you might want to make use of a few of these code snippets using hooks.
Useful code snippets for WordPress from WP Theme Detector – quite a few of these are actually making use of various WordPress hooks (Disclaimer: not tested or endorsed).
More useful code snippets for WordPress from WP Kube using various hooks.
WordPress Hooks: Your Imagination Is the Only Limit
As you’ve seen in this article, WordPress hooks give you much power and possibilities in extending the core WordPress functions. This gives great power to WordPress designers, developers and even freelancers who just want to perform small tweaks to WordPress.Tags: