As some of you probably know, my first encounter with WordPress was actually the API I’d like to briefly introduce today. The first thing I did for WordPress was write a plugin. I already knew PHP pretty well back then, and a colleague needed something in WordPress that wasn’t part of the Core. After a quick search, I found out that you can easily extend WordPress yourself without ever having to touch the Core. And that’s how my first plugin was born.
Without a doubt, the Plugin API is one of the most important parts of WordPress. It’s the only way to build a website exactly the way you need it. So let’s take a closer look at the API.
What does the API do?
The Plugin API is probably hard to pin down, because there aren’t “the functions” that it contains. If you boil it down to the bare essentials, I’d say the Plugin API is primarily one thing: hooks. You could also take a broader view, but then essentially every public function in the Core would fall under it, since all of these functions could be used in a plugin. So let’s focus on the essentials in this blog post: the hooks – or, more precisely, actions and filters.
At first glance, the two types of hooks aren’t that different, and they’re often confused – which, unfortunately, often works just fine. But there is a logical distinction:
- An “action” executes a piece of code at a specific point in time but does not return anything
- A “filter” modifies a passed-in value and returns it
Internally, actions in WordPress are filters that simply do not return a value. The function looks like this:
function add_action( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) {
return add_filter( $hook_name, $callback, $priority, $accepted_args );
}
So you can easily mix up add_action() and add_filter(), and your code still works. But of course, you should make sure to use the correct function to clarify the expected behavior.
Which functions should I know?
I’ve already mentioned two functions that are arguably among the most important ones you need to know. With add_action() and add_filter(), you can attach your own function to a hook. This is important for anyone who wants to customize existing code in the Core, in plugins, or in a theme.
If you develop plugins or themes yourself, their counterparts are important. With do_action() and apply_filters(), you can then call the attached functions and allow others to customize your code at specific points.
If you want to remove a hook, you can use remove_action() and remove_filter() to remove a specific function from a hook. Here, you must specify the hook name, the callback function, and the priority – just as you did when adding it. If you want to remove all functions for a hook, you can use remove_all_actions() or remove_all_filters(), respectively, and you’ll only need the hook’s name. However, you should only do this for your own hooks and not for Core hooks, because otherwise many plugins might no longer function correctly.
If you want to check whether a callback function is registered for a hook, whether it has already been executed at least once, or whether you’re currently inside a hook’s callback function, you can use the functions has_action(), has_filter(), did_action(), did_filter(), current_filter(), doing_action(). The names here are sometimes similar between actions and filters, but sometimes completely different. This can be a bit annoying, but over time you’ll memorize the names. Finally, there are the functions apply_filters_deprecated() and do_action_deprecated(), which you can use to mark “deprecated” hooks in your code. Anyone using these hooks will then receive a warning that the hook is deprecated and, in most cases, will also be told which hook replaces it. These functions are often introduced in one version, and the deprecated hook is then completely removed several versions later.
What does this look like in practice?
As a practical example, we could extend yesterday’s code with a filter. In the REST API response, we’ll add a filter that allows others to specifically adjust the word count of the excerpt. We’ll integrate the filter into the callback function advent_calendar_get_post() as follows:
/**
* Filters the number of words in the excerpt of the endpoint response.
*
* @param int $length Number of words. Default 30.
* @param WP_Post $post The requested post.
*/
$excerpt_length = (int) apply_filters(
'advent_calendar_excerpt_length',
30,
$post
);
// …
'excerpt' => wp_trim_words( $content, max( 1, $excerpt_length ) ),
You should always choose a prefix for your own hooks, preferably one that matches the prefixes of the functions. Here, the plugin or theme’s slug has become the de facto standard.
In addition to the hook’s name, the second parameter is particularly important. It’s the value that’s used when nobody changes it with a callback.
You can pass additional parameters when calling the hook – in our example, the current post. To let others know what additional parameters the hook accepts, you should list them in a DocBlock. Specify the default value for the first parameter here.
Since you can’t know whether others are using the filter correctly – and an incorrect return value can lead to errors – you should validate the return value. Since we need a number here, we can simply cast it to (int). If, for example, a string that isn’t a number is returned, it will be converted to 0, but the max() function will ensure it’s at least 1. So your code will still work.
Now that the filter has been added, others can use it. This is done with add_filter() and a custom function. The result might look like this:
function my_excerpt_length( $length, $post ) {
if ( has_tag( 'gutenberg', $post ) ) {
return 50;
}
return $length;
}
add_filter( 'advent_calendar_excerpt_length', 'my_excerpt_length', 10, 2 );
In this code example, the optional $post parameter is also used, and the value of $length is adjusted only if the post has a specific tag. For this to work, you must specify the fourth parameter when calling add_filter(); otherwise, you’ll get an error and the parameter won’t be available. If you don’t need the parameter, just leave out the third and fourth one – but then your callback function only takes one parameter as well.
It’s important that you always return the original value if your function doesn’t intend to change it. If you don’t, the value will suddenly be empty, and this will most likely cause things to break.
Another “rule” for filters: They shouldn’t have any “side effects.” In other words, only the value should be changed and returned. So, don’t do anything within the filter that you would normally do in an action, such as modifying data in the database, writing to a log file, sending emails, etc.
What should I watch out for?
With filters, it’s really important to always return a value – if in doubt, return the unmodified original value. You should also avoid the side effects mentioned above. A common mistake is to use echo to output the value instead of using return to return it. That usually doesn’t work.
If you have additional parameters, always use the fourth parameter, $accepted_args; otherwise, the parameters won’t be passed to your callback function. Before that comes the priority. Use either the default value 10 or a value that’s slightly higher or slightly lower. Please never use PHP_INT_MAX, because if everyone assumes their code should always run last, it won’t work. A value of 100 or 1000 is often more than enough here.
It’s also important to add your callback functions at the right time. If a hook has already been executed before you attached your function, nothing will happen. For plugins, I recommend grouping the calls to add_action() and add_filter() into a single callback function on plugins_loaded; for themes, on after_setup_theme. By then, all other plugins will already be loaded, and you can, for example, remove their callbacks as well. For hooks that fire earlier, such as muplugins_loaded or plugins_loaded itself, this is of course too late. You’ll need to add those right when the plugin file loads. And, of course, plugins_loaded and after_setup_theme are also hooks – or, more precisely, actions. 😉
To allow others to remove your callbacks, please avoid using closures whenever possible. The same goes for methods of objects: you can only remove them if you have the exact same instance.
If you provide hooks yourself, be aware that they become part of a “public API.” So make sure that code using your hooks still works even if you change the code, and use apply_filters_deprecated() if necessary to let others know they need to update their code.
When should I use it?
If you need to customize anything in a plugin, theme, or the Core, hooks are the first choice. Not all plugins always have hooks in the right place, but they often use Core functions that provide a hook. It’s (almost) always possible to customize code without modifying the code itself. If that’s not possible, open a support ticket or a pull request to have a hook added to the code. When I’m developing my plugins, I don’t always know which parts others might want to customize, so I’m always grateful for such suggestions.
In addition to hooks, you can of course also create a configuration page. But I prefer plugins that just work without requiring a lot of configuration. And building a configuration page is very time-consuming – but more on that another day. 😉
By the way, hooks aren’t just available in PHP – they’re also available in JavaScript for the Block Editor. But we’ll cover that in a future blog post as well.
Where can I find more information?
What should I remember?
- Actions execute code, so they generally have side effects
- Filters receive a value and must return it, but should not have side effects
- The priority and number of arguments determine when and with what your callback runs
- Creating your own hooks makes your plugin extensible, but they constitute a public API: You must pay attention to the prefix, documentation, and backward compatibility.
I hope I was able to give you a brief introduction to hooks. Tomorrow, we’ll talk about an API that I’ve already briefly mentioned here. So, can you guess which one it will be?