If you’re into WordPress development, you can not ignore Actions & Filters for a long time.
You need to go into depth and understand the meaning of those hooks in WordPress and how to use them.
Changes to the core functions of WordPress are strictly forbidden as you know, so in case you need to change a certain functionality or alternatively create a new one, hooks are the way to do it.
Hooks in WordPress allow WordPress developers to attach the code they wrote to the core of WordPress, theme, and plugins.
In this post we will explain what hooks are, we will go through different types of hooks.
And we will see some examples and create our own hooks.
- Explanation of the terms
- Types of operations and filters
- Attach to hooks or remove an existing hook?
- Examples of using hooks – WordPress
- 1) Add a link to the footer page
- 2) Change excerpt length
- 3) attach to hook when post published
- 1) Attach to the hook where you add assets (scripts and CSS files)
- 5) Add the page number to the meta title created by Yoast SEO
- 6) Remove canonical addresses from search results pages on your site
- Creating new Hooks
- So what did we learn?
Explanation of the terms
A hook is a generic term in WordPress that refers to locations where you can add your own code or change the actions that WordPress performs or prints by default. There are two types of hooks Actions & Filters. For convenience, we will refer to them in this post as actions and filters.
Action
An action in WordPress is a hook that is performed at a specific time when WordPress wanted and allows you to perform a certain action at the same time.
Action can be creating a custom post (Custom Post Type) when WordPress is initialized or even sharing your post on Facebook when you post.
In working with an action you do not receive or change information, but simply get a place to add and run your own code at a certain time during the WordPress Runtime run.
Filter
A filter in WordPress on the other hand allows you to modify the information before it is sent to the database or browser. An excellent example of using a filter is adding a certain code at the end of each post, or changing the length of the excerpt displayed for each post for example.
When working with a filter we get a piece of information, and then (at the end of the function) we have to return the same piece of information (after the change you made to the same information).
Types of operations and filters
In WordPress Codex there are two important pages that can help you find out which hooks are available to you.
Let’s look at the list of existing types of actions and they are divided into the following categories:
- Actions Run During a Typical Request
- Actions Run During an Admin Page Request
- Post, Page, Attachment, and Category Actions (Admin)
- Comment, Ping, and Trackback Actions
- Blogroll Actions
- Feed Actions
- Template Actions
- Administrative Actions
- Dashboard “Right Now” Widget Actions
In WordPress Codex you will find a similar page that shows the existing filters at your disposal and the same filters are also divided into categories:
- Post, Page, and Attachment (Upload) Filters
- Comment, Trackback, and Ping Filters
- Category and Term Filters
- Link Filters
- Date and Time Filters
- Author and User Filters
- Blogroll Filters
- Blog Information and Option Filters
- General Text Filters
- Administrative Filters
- Rich Text Editor Filters
- Template Filters
- Registration & Login Filters
- Redirect/Rewrite Filters
- WP_Query Filters
- Media Filters
- Advanced WordPress Filters
- Widgets
- Admin Bar
Many of those filters are divided into two sub-categories, reading from the database and writing from the database. These depend on whether you are reading from the database before displaying content on the page or the edit page, or if you are writing content before storing it in the database.
Working with hooks in WordPress starts with understanding which hooks you need to attach the code to and only then write the code that modifies the information you need (filter) or performs an action that you want to run (action).
Attach to hooks or remove an existing hook?
If you want to attach your own functions, the procedure is quite simple, but you need to know a few things first. For actions, you will want to know the hook name and when it should run.
For filters, you are required to know the name of the hook as well, but you are also required to know what type of value you are getting and what you need to return.
In addition to these, you need to know the name of the function in which your code is located.
Lets see how to attach to a action
add_action( $hook, $function_to_add, $priority, $accepted_args );
The parameters needed for the add_action function are the hook to which you want to attach 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 determines the order of priority of the functions attached to that specific hook. A higher value will run at a later stage and vice versa. The last parameter is less useful and exists for situations where you want to pass or receive multiple arguments.
Please note that the default priority parameter is 10.
How to attach to a filter
add_filter( $tag, $function_to_add, $priority, $accepted_args );
The add_filter function works in the same way as add_action, but remember that for a filter – the function function_to_add must get a value and return it at the end of the function.
How to remove attached hook
Removing the attached hooks is very simple. Use the remove_action or remove_filter function along with the hook name, function name, and priority. Also in this case the priority is optional and helps for situations where you are required to remove a coupling to a function that is attached more than once and you want to remove only one attach hook from the same function.
remove_action( $tag, $function_to_remove, $priority );
remove_filter( $tag, $function_to_remove, $priority );
Having understood the basics of how to remove and attach functions, let’s give a look at some real-world examples of multiple hooks in action.
Examples of using hooks – WordPress
There are over 200 hooks in WordPress. Of course, plugins and templates have hooks of their own so the number of hooks is actually almost infinite.
Take a look below and you will see some examples of the use of WordPress hooks and the WordPress SEO by Yoast plugin.
1) Add a link to the footer page
<?php
/****** BEGIN HERE ******/
function add_footer_link() { ?>
<a href="https://minopress.com">MinoPress - Premium WordPress Themes</a>
<?php
}
add_action( 'wp_footer', 'add_footer_link' );
In the example above you can see a function called add_footer_link attached to a WordPress hook (action) called wp_footer. This allows you to add a specific code (in our case a link to the home page), in the location of the same hook (its location in the potter).
2) Change excerpt length
function excerpt_length_example( $words ) {
return 25;
}
add_filter( 'excerpt_length', 'excerpt_length_example' );
In this example, we stick to a filter called excerpt_length that provides us with an integer that determines the number of words that will appear when using the the_excerpt() function in your template.
If you are not sure what kind of value the filter should have, look in the WordPress core code for apply_filters (‘filter_name’ and take a deeper look at what is happening with that filter.
3) attach to hook when post published
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 will see that we are clinging to a hook (action) called publish_post running while a post is published. You can use it to do something at this point like post your Twitter post.
The full code is a little more complicated and beyond the scope of this guide, but it provides a great example of the action you can take whenever a post is posted on your WordPress websites.
1) Attach to the hook where you add assets (scripts and CSS files)
function themeslug_enqueue_style() {
wp_enqueue_style( 'my-css', 'style.css', false );
}
function themeslug_enqueue_script() {
wp_enqueue_script( 'my-js', 'script.js', false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' );
I think you saw something similar to the following code. It is widely used and learned at a very early stage in the world of WordPress development.
In this case, we attach a hook (action) called wp_enqueue_scripts to add assets – Javascript files 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 correct than “hard coding” which is not hard coding.
This is the place to point out, if I was not clear – you can attach as many functions as you want to the same hook!
5) Add the page number to the meta title created by Yoast SEO
As we mentioned at the beginning of the article, many plugins provide us with hooks in order 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 case, the promoter of one of the companies to which I provide a service asked to add the word Page and the page number at the end of the meta title on those pages on the paginated pages of the site.
For example, page three will appear at the end of the meta title and so on for the titles in the other numbered pages, all this while on page number one this change will not be made. Since in the case of that specific site the meta title was created using the WordPress SEO by Yoast plugin, it was right to look for a Yoast filter that allows modification to the page title.
A quick search led to a hook (filter) called wpseo_title that accepts the page title as a value and returns the title after the change you made. We have created a function called change_yoast_title in which we check whether the page is numbered or not, and if so add the requested text at the end of the title.
6) Remove canonical addresses from search results pages on your site
An action that SEO will likely like. Assuming you are using Yoast SEO the following filter will remove the canonical URL from the WordPress search results pages:
function yoast_remove_canonical_search( $canonical ) {
if( is_search() ) {
return false;
} else {
return $canonical;
}
}
add_filter('wpseo_canonical', 'yoast_remove_canonical_search');
Creating new Hooks
In order to use the functionality of the hook to create your own hooks, you do not 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 the functions.php file (or your plugin):
function custom_hook() {
do_action('custom_hook');
}
The code above will add an action called custom_hook to the WordPress hookup library and allow you to use it anywhere you want in your template. Of course, you should call Hawk a more logical name that describes the function being performed.
2) Add the hook in your theme
Add the call to the function wherever you want in your theme:
<?php custom_hook(); ?>
You can simply add do_action (‘custom_hook’); In the format directly.
With these two snippets, a new hook is added to your theme through which you can run any function you want using the add_action function we explained earlier. Now all that remains is to add the function that performs some action.
3) Add the function of the hook itself
Now, to add your own code to this location you must 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 avoid errors in case there is already a function with that name.
So what did we learn?
II hope we learned the basics of how hooks work in WordPress and how to use them.
WordPress uses actions and filters to expand its capabilities – from simple examples as we have presented to hooks for complex plugins such as Woocommerce.
If you liked the guide feel free to share and write your thoughts in the comments below… -:)