If you’re into WordPress development, you won’t be able to ignore hooks (Actions & Filters) for a long time before you have to delve deep and understand the meaning of those hooks in WordPress and how to use them.
Changes to WordPress core functions are strictly forbidden, so if you want to modify a specific functionality or create a new one, hooks are the way to do it. Hooks in WordPress allow developers to “attach” their code to the WordPress core, themes, and plugins.
In this post, we’ll explain what hooks are, go over different types of hooks, see some examples of hooks in action, and even show how to create your own hooks.
Explanation of Terms
Hook: A generic term in WordPress referring to locations where you can add your own code or change the actions performed or output by WordPress. There are two types of hooks: Actions & Filters.
What is an Action in WordPress?
An action in WordPress is a hook that occurs at a specific time when WordPress runs, allowing you to perform a specific action at that time. For example, an action could be creating a custom post type when WordPress is initialized or sharing your post on Facebook when you publish it.
How about Filter in WordPress?
A filter in WordPress, on the other hand, allows you to modify data before it is sent to the database or the browser. A great example of using a filter is adding specific code at the end of each post or changing the length of the excerpt displayed for each post.
Working with hooks in WordPress begins with understanding which hook you need to attach your code to and then writing the code that modifies the information you need (filter) or performs an action you want to run (action).
How to attach or remove hook attachments?
If you want to attach your own functions, the procedure is quite simple, but you need to know a few things beforehand. For actions, you’ll want to know the hook name and when it should run.
For filters, you need to know the hook name as well, but you also need to know what type of value you receive and what you need to return. In addition, you need to know the name of the function that contains your code.
How to attach to an action
add_action( $hook, $function_to_add, $priority, $accepted_args );
The required parameters for the add_action
function are the hook you want to attach to and the name of the function you want to attach to it.
The priority
parameter is optional and represents an integer between 1 and 999 that sets the priority order of functions attached to the same specific hook. A higher value will run later, and vice versa. The last parameter is less useful and is for situations where you want to pass or receive a number of arguments.
For your information, the default value for the priority parameter is 10.
How to attach to a filter
add_filter( $tag, $function_to_add, $priority, $accepted_args );
The add_filter
function works similarly to add_action
, but remember that for a filter, the function_to_add
parameter should accept a value and return it at the end of the function.
How to Remove Hook Attachments
Removing hook attachments is very simple. Use the remove_action
or remove_filter
function along with the hook name, function name, and priority.
In this case as well, the priority is optional and helps in situations where you need to remove an attachment to a function that is attached more than once, and you want to remove only one attachment of the same function.
remove_action( $tag, $function_to_remove, $priority );
remove_filter( $tag, $function_to_remove, $priority );
After understanding the basics of how to remove and attach functions, let’s look at some real-world examples of the use of hooks.
Examples of Using Hooks – WordPress
There are over 200 hooks in WordPress. Of course, plugins and themes have their own hooks, so the number of hooks is almost infinite. Take a look below and see some examples of using hooks in WordPress and in the WordPress SEO by Yoast plugin.
1. Adding a link to the home page in the footer
<?php
/****** BEGIN HERE ******/
function add_footer_link() { ?>
<a href="https://savvy.co.il">Savvy.co.il - WordPress Developer & Designer</a>
<?php
}
add_action( 'wp_footer', 'add_footer_link' );
2. Changing the Excerpt Length
function excerpt_length_example( $words ) {
return 15;
}
add_filter( 'excerpt_length', 'excerpt_length_example' );
In this example, we attach to the excerpt_length
filter, which provides us with an integer determining the number of words that will appear when using the the_excerpt()
function in your template.
If you’re unsure what type of value the filter is supposed to receive, search the WordPress core code for
apply_filters( 'filter_name'
and take a closer look at what happens with that filter.
3. Attaching to the Publish Post Action
function publish_post_tweet($post_ID) {
global $post;
// Code to send a tweet with post info
}
add_action('publish_post', 'publish_post_tweet');
In this partial example, you can see that we attach to the publish_post
action, which runs when a post is published. You can use it to perform something at that point, like publishing your post on Twitter.
The complete code is a bit more complex and beyond the scope of this guide, but it provides an excellent example of an action you can take every time a post is published on your WordPress site.
4. Attaching to the Enqueue Scripts and Styles Action
function themeslug_enqueue_style() {
wp_enqueue_style( 'core', 'style.css', false );
}
function themeslug_enqueue_script() {
wp_enqueue_script( 'my-js', 'filename.js', false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' );
I assume you’ve seen something similar to the following code in many articles on this blog. It is widely used and learned very early in the world of WordPress development. In this case, we attach to the hook (action) named wp_enqueue_scripts
to add JavaScript and CSS files on the client side (Frontend) in your WordPress template. This is the preferred way to add assets to WordPress sites and is more convenient than “hard coding.”
This is the place to mention, if it wasn’t clear – you can attach as many functions as you want to the same hook!
5. Adding the Page Number to the Meta Title Created by Yoast SEO
As mentioned at the beginning of the article, many plugins provide us with hooks to modify their functionality.
function change_yoast_title($title) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ( is_paged() ) {
return $title . ' - Page ' . $paged;
}
else {
// first page of pagination
return $title;
}
}
add_filter('wpseo_title','change_yoast_title');
In this real-world case, the marketing manager of one of the companies I provide services to wanted to add the word “Page” and the page number at the end of the meta title on paginated pages of the site.
For example, on page three, “Page 3” will appear at the end of the meta title, and the same for the titles on the other paginated pages. This modification won’t occur on the first page. In the case of this specific site, the meta title is generated by the WordPress SEO by Yoast plugin, so it was appropriate to look for a Yoast filter that allows modification of the page title.
Fast Search led to a filter named wpseo_title
, which takes the page title as a value and returns the title after the modification you made. We created a function called change_yoast_title
in which we check if the page is numbered or not, and if so, it adds the requested text at the end of the title.
6. Removing Canonical URLs from your search results pages
An action that SEO experts will likely appreciate. Assuming you are using Yoast SEO, the following filter will remove the Canonical URL from the search results pages of WordPress:
function yoast_remove_canonical_search( $canonical ) {
if( is_search() ) {
return false;
} else {
return $canonical;
}
}
add_filter('wpseo_canonical', 'yoast_remove_canonical_search');
Create Your Own Hooks
To use the functionality of hooks to create your own hooks, you don’t need to create special functions – you can use the same function that WordPress uses called do_action
.
1. Define Your Hook
Add the following code to your functions.php
file (or your plugin):
function custom_hook() {
do_action('custom_hook');
}
The above code will add an action named custom_hook
to the WordPress hooks library, allowing you to use it anywhere in your template. Of course, you should call the hook a more logical name that describes the performed function.
2. Add the Hook to Your Template
Add the call to the function wherever you want in your template:
<?php custom_hook(); ?>
You can simply add
do_action('custom_hook');
directly in the template.
With these two snippets, your template is equipped with a new hook through which you can run any function you desire using the add_action
function explained earlier. Now, all that’s left is to add the function that performs a specific action.
3. Add the Function Itself
Now, to add your own code at this point, you need to use the following code:
if ( ! function_exists( 'your_function_name' ) ) {
function your_function_name() {
// Your custom code goes here
}
add_action( 'custom_hook', 'your_function_name' );
}
Note that we wrapped the function in
if_function_exists()
to prevent errors in case a function with the same name already exists.
Now, to understand the power of hooks, move the location of the function call to a different place in the template, and you will see that “Hello WordPress” will be printed in the new location.
So, What Have We Learned?
I hope we learned what hooks are, namely actions and filters in WordPress, as well as the basics of how they work. WordPress uses actions and filters to expand its capabilities – from simple examples as shown to hooks for complex plugins like WooCommerce.
If you enjoyed the guide, feel free to share and share your thoughts in the comments below… 🙂