If you look at a WordPress page with any of the available developer tools, you might get the impression that it is mainly made up of HTML and CSS with some occasional JavaScript.
However, what you see there is only the end product.
In the background, much of any given WordPress page is actually constructed from PHP functions and database queries. These get interpreted by the browser who then spits out the page in a viewable form.
While CSS works well to make superficial changes (colors, sizes, etc.), if you want to make bigger, structural alterations, you will need to deal with the source code.
One possibility to do so is to locate the respective lines of code in the core files and replace them with your own. It’s a method that does (unarguably) work and that some people continue to use.
However, the disadvantage of this practice is that with the next WordPress update all your customizations will vanish. The core files get overwritten and — poof — all your changes are gone.
Plus, not updating isn’t a good idea, since it poses a serious security risk. So, what to do?
Thankfully, there is a way to change the code in WordPress without actually changing it. Sounds impossible? Well, let me introduce you to WordPress hooks.
What are WordPress hooks?
Hooks are an incredibly powerful tool. Knowing how to leverage them is one of the most important concepts for both plugin and theme development.
For example, hooks are widely used in theme frameworks such as Genesis to allow for easier theme customizations. But don’t let that scare you off.
Even if you are not a developer and just looking for a more elegant and efficient way to make changes to your site, you can still benefit from learning about WordPress hooks.
So what are they?
First of all, hooks are easy to spot. Anytime you see a piece of code wrapped into do_action()
or apply_filters()
function, you have found yourself a hook. They appear both in the WordPress core as well as in plugins and themes.
For example, in the header section of many themes, you will find a line of code similar to this one:
[php]<?php wp_head(); ?>[/php]
If you look into the WordPres core files to see what’s behind wp_head
, you will find the following:
[php]function wp_head() {
do_action( ‘wp_head’ );
}[/php]
Not much happening here. This piece of code creates a function called wp_head
and turns it into a hook (do_action()
, remember?).
How is that helpful or even necessary? Well, I’ll tell you.
While the code doesn’t really fulfill any function on its own, it turns wp_head
into a sort of anchor.
This means you can hook other functions and code to it that will then be executed once WordPress processes the wp_head
function.
Consequently, your custom code does not need to be physically placed in the same location but instead gets pulled in from the outside.
That way, you can execute your own functions within the core construct without changing any code in the core files. Pretty sweet, huh?
The best part is that no matter how often you update WordPress, your changes will stay in place and won’t be overwritten.
Convinced? Then let’s dive a little deeper.
Your main tools: actions and filters
To alter functionality through WordPress hooks, we rely on two principal ways: actions and filters. The corresponding functions in WordPress are add_action()
and add_filter()
.
The term hooks is often used as an umbrella term for these functions and at the same time for the placeholders we can hook them into.
To make matters more confusing, sometimes you will also hear of action hooks and filter hooks. However, don’t worry about this too much. It’s more important that you understand the methodology behind it.
While actions and filters are generally very similar in their syntax, the way they work is quite different.
When you hook an action to a placeholder, it is executed in addition to any functions already present in that particular location.
For that reason, action hooks are used for adding stuff to your site. For example, if you want to create a new widget area in the header or footer of your website, you would do so with an action hook.
Filters, on the other hand, modify existing functionality. They sit between the database and the browser and are able to tweak code that is being passed in either direction.
One example for the use of a filter hook would be if you wanted to replace the “Howdy” greeting in the WordPress admin bar with custom text.
The main difference between actions and filters is that the latter must return a parameter back to the original function. That means they take any argument from the code they are meant to filter, change it in some way, and then give the tweaked parameter back to their predecessor.
Actions, on the other hand, merely slap some additional code onto the function they hook into and are generally quite unconcerned with what else is already there.
Understood? Don’t worry, if you are still a bit hazy on the details, it will all get clearer once we get to the actual code.
The structure of the hook
How do you use actions and filters? The general structure looks a little something like this:
[php]add_action ( ‘hook_name’, ‘your_function_name’, [priority], [accepted_parameters] );
function your_function_name() {
// code goes here
}[/php]
As you can see, a filter or action hook is made up of four main parts. It’s not necessary to include all of them at all times, but you should be aware of their existence. Let’s go over each in detail.
1. Hook_name
The name of the location where we want our custom functionality to be executed. This will be the function name that we have found wrapped into do_action()
or apply_filters()
. In our earlier example, that was wp_head
.
Note: The hook name is also sometimes called tag.
2. Your_function_name
Here goes the name of the function that we will hook to our tag. It can be your own, a standard PHP function, or one existing in the WordPress core.
If you decide to write your own, here is a few things to keep in mind:
First, make sure your name only consists of letters, numbers, and underscores. Don’t use hyphens to separate words, this goes against WordPress coding standards.
Next, be aware that PHP doesn’t allow more than one function with the same name. Therefore, it is important that you choose a unique name to avoid a collision.
A common practice to achieve this is to prefix the name with your initials or some other uncommon identifier, for example nick_awesome
_function
.
You should also make sure that your function names are understandable and make sense. While you can choose any name, it’s much easier for others to build on your work if your code is self-documenting.
3. Priority
The priority argument determines the order in which code is executed if several function are hooked to the same placeholder.
Priority is determined by a number between 1 and 999 with the default being 10. The lower the number, the earlier the function will run.
While this is often not important, in some cases stating priority is essential. This part deserves special attention for filter hooks, as they might overwrite one another.
It’s also important to note that priority takes precedence to the order of functions in a file. Even if one is at the very beginning and another at the very end, if the latter has a higher priority, WordPress will run it first.
4. Accepted_parameters
This statement gives the number of parameters passed by any function. The default setting is one.
Defining the accepted parameters is generally optional. However, it is often necessary for filter hooks especially if they pass more than one argument. In that case, the number of parameters has to be clearly defined.
After that is done, all that’s left is writing the function you want to execute. Sounds easy, right? Ok, enough with the theory, let’s look at some concrete examples.
Examples
For the following use cases, I am using a development site running on the Twenty Fifteen theme. Just in case you are wondering about the hook names.
First, I want to make some changes to my footer.
When I look at the footer.php
file of the theme, I come across the following code:
[php]do_action( ‘twentyfifteen_credits’ );[/php]
If you have been following along, you will know that this is a dead-on sign for an action hook. In this case, I want to add some personal greeting to the footer of my site. I can do so, like this:
[php]add_action(‘twentyfifteen_credits’, ‘nick_footer_greeting’);
function nick_footer_greeting() {
echo ‘Hi, thanks for coming to my site!’;
}[/php]
As you should understand by now, with the first line I am attaching a custom function called nick_footer_greeting
to the Twenty Fifteen credits.
After that comes the custom code. All I do here is tell WordPress to print a special greeting in addition to the Twenty Fifteen credits.
The result looks like this:
That wasn’t so hard now, was it? Don’t worry, filters aren’t either.
In my next example, I want to make a change to the title of my sticky posts. Whenever I stick a post to my front page, I want the words “Breaking News” to appear in front of the title.
To that end, I will create a custom function like this:
[php]function nick_breaking_news_filter($title) {
if (is_sticky() && in_the_loop()){
return ‘Breaking News: ‘.$title;
}
else {
return $title;
}
}
add_filter(‘the_title’, ‘nick_breaking_news_filter’);[/php]
The hook I am targeting is the_title
. It includes a parameter named $title
, which I can filter here.
My function is basically telling to WordPress take this parameter, check whether the post it’s applied to is a sticky post and if so attach “Breaking News:” in front of it.
Here’s the result:
Looks good, doesn’t it? As you can see, these kinds of modifications can be done pretty easily.
One more thing: You might have noticed that in one case I first created the function then the hook, while in the other I first wrote the hook, then my custom code. Both will work, it is up to you which one you like better.
How to implement WordPress hooks
Alright, by now you should have a good understanding of what hooks do, what they look like and how to write your own. However, the question remains where to place your custom code.
Hooks can be implemented in two ways: Either by pasting them into functions.php
(preferably in a child theme) or by creating a custom plugin.
While the choice is up to you, the latter method has the advantage that you can switch your functions on and off directly from the WordPress backend. No dialing into your server required.
If you are intimidated by the prospect of creating your own plugin, don’t be. It’s really not that difficult. If you’ve ever set up your own style sheet or pasted code in the functions.php
file, you are good to go.
The only difference in going the plugin route is that instead of having all functions in one file, you put each of them in their own and add a plugin header, like this:
[php]<?php
/*
Plugin Name: My Custom Plugin
*/
// your custom function and hook go here[/php]
Now all you need to do is place your file within wp-content/plugins
(with or without its own directory) and you are done.
If even this overwhelms you (don’t worry, I have been there), there is also a plugin called Pluginception, which can create the header for you.
Removing WordPress theme hooks
There might be times when you want to remove actions or filters entirely.
This can be the case if there is a conflict with one of your own functions or if you want to unhook an action or filter in one place and re-hook it somewhere else.
In both cases, this can be achieved via remove_action()
and remove_filter()
.
For example, to prevent your WordPress site from pinging other blogs when you publish a new post, you could use the following code:
[php]remove_action(‘publish_post’,’generic_ping’);[/php]
If you want to execute an unhooked function in some other place, you could do so via the familiar add_action()
.
Just a quick caveat: If the hook you want to remove has a priority statement other than the default 10, you need to specify this when you unhook it. Also, of course, don’t remove anything unless you know what you’re doing!
Resources
One of the biggest parts of working with WordPress hooks is finding the right placeholders. To make this a little easier, here are three resources that will help you with the search.
1. WordPress Codex: Action Reference
A (hopefully complete) list of all action all action hooks present in WordPress core.
2. WordPress Codex: Filter Reference
The same list for WordPress core filter hooks.
3. WordPress Hooks Database by Adam Brown
Find any hook ever used, the version they were introduced in and whether or not they are still valid. The database also has many filter options for displaying only new hooks, deleted hooks, hooks by version, and more.
Summing up
WordPress hooks are an essential and powerful tool not only for WordPress developers. Knowing how to use hooks allows any WordPress users to modify core functionality without touching any files.
Actions and filters allow you to add and tweak functions and achieve pretty much any imaginable outcome. Paired with the ability to remove hooks when necessary, this means you can rearrange your site’s layout at will.
The best part: Because the core files stay untouched, all modifications are update-proof.
I can only recommend getting familiar with using WordPress hooks. They make working with the platform much more dynamic. Plus, once you move on to theme frameworks and other themes that offer modification via theme hooks, you won’t get around them.
Are you familiar with WordPress hooks yet? Any resources or thoughts to add? Please share in the comments.
12 Comments