Skip to content

Understanding WordPress Hooks

WordPress, the most popular CMS (Content Management System) is known for its flexibility. It’s highly customizable, and making any changes is incredibly easy. One of the most important aspects of WordPress and its flexibility is WordPress hooks. In this post, we are going to explore what exactly a WordPress hook is, how it works and how we can use them.

Users are able to extend WordPress functionality by using plugins. WordPress.org has more than 55,000 plugins in its repository – many of which are free. There are some premium plugins hosted by WordPress.org as well.

So, even by looking at the plugin’s stats, we see that a lot of developers create plugins for WordPress. This is due to the flexible nature of the WordPress structure. So where do hooks come into play? They are an integral part of how plugins work with WordPress core.

What is a WordPress hook?

Let’s break it down. A WordPress hook will let you know that something is happening. In other words, a hook will let you run custom codes when loading a WordPress website to add, remove or modify certain functionality or data. You can do the following with a hook:

  • Executing a code to send a welcome email right after a new user has registered to the site.
  • Running a custom code to clear site cache after saving new changes in customizer.
  • Modifying the default admin footer text.
  • Changing the label of the “Register” button on the registration page.
  • Modifying the markup of the page right before the page loads.
  • Including new styles in certain conditions.

The main point of using hooks is that you don’t need to touch WordPress core files that are required by WordPress to work. If you edit any file in WordPress core, you’ll lose it after updating WordPress.

These are some basic examples of WordPress hooks. As previously mentioned, they work with certain functionality or data. So, there are two different types of WordPress hooks:

  • Actions
  • Filters

WordPress Actions

Action hooks can be used to add custom functionality when needed. For instance, imagine that you want to run a code to log the last login time for each user. You’ll need to run a piece of code that records the time right after a user logs into the site. So you’ll need to run an additional functionality at a certain time. In this case, we would have to use action hooks. Action hooks work with functionality – they are doing something new.

How do action hooks work?

Action hooks are similar to informing everyone that you want to do a specific thing such as saying, “Hey buds, I’ve just arrived” or “Bye guys, I’m leaving.” When you inform others, they are aware of what you did or what you want to do, and they can say something in response, remind you of something or react in any other type of way.

While WordPress is loading and reaches a specific point, it’ll let us know about it. So, you can run your codes to add specific functionality or to extend existing functionality.
Some examples of actions include the following:

wp_head When you reach the <head> tag, WordPress lets you know by running the wp_head hook. Remember it as a name. We will provide you with some codes and an explanation about how to use hooks.

publish_post This runs when a post is published or if it is edited and its status is changed to “published.” So, Imagine that you want to tweet a post automatically after publishing it to your WordPress site. This hook makes it easy for you to do it.

wp_footer This action hook is triggered near the tag. That means you are reaching the end of document markup. Many developers use this hook to include their javascript files to the footer of the page.

WordPress Filters

Photo by Luca Bravo on Unsplash

Filter hooks work with data. By data, we mean a simple text, HTML markups and even a PHP variable that could be the value of an option. This means that you can change an option value on the fly. Or you can change a certain text in the admin dashboard without editing WordPress core files. Also, filters could be used to modify multiple things at the same time. For example, you can add a new class name and data attribute simultaneously to the navigation menu items using a filter.

How do filter hooks work?

Filter hooks differ from action hooks. When you reach a certain code, WordPress allows you to make changes to something. Imagine that your child wants to go to school and right before going out, you put an extra book in their backpack. In this example, you’ve changed the content of the backpack and filtered it when you had access to it. Filters work in the same way. They will let you know that content is going to be printed or when an option is going to be used – and you’ll be able to modify it if you want.

Some real example of filters are:

login_erros This runs whenever an error is going to be shown to the user in the login page.

body_class This fires (runs) while generating the tag. Use this filter hook if you want to modify the class names of the body tag.

pre_delete_post This fires right before deleting a post. You may want to avoid sending them to the trash and delete them completely. This filter hook will be useful for you.

How to use WordPress hooks

We’ve covered the basics of WordPress hooks. It’s time to learn code and use actions and filters in the real world. In this section, we’ll see some new things such as Hooked functions, Hook priority and Hook arguments.

Basic WordPress hooks usage

add_action( ‘init’, function(){
     // Do something.
 } );
Code explanation:

add_action: This is a function from WordPress. You’ll need to use this whenever you want to register a new action hook (run an action).

init: This is the hook name. Each event has a unique hook name. You can find a list of existing WordPress hooks on the Plugin API/Action reference page.

function(): This is the callback. The code that you want to execute when reaching the event.

For filters, it is a bit different:

add_filter( ‘excerpt_length’, function( $value ){
     // Do something and change $value.
     return $value
 } );

add_filter: Same as actions, this is a function name from WordPress. You’ll need to use this whenever you want to register a new filter hook.

excerpt_length: Again, this is the hook name. Hook names are meaningful. So, while using excerpt_length you can expect that it will change the excerpt length of the post excerpt.

function(): This is the callback and the code that you want to execute in order to change something.

And the big difference with actions:

return $value

Filters need to return something. Why? Because using filters, you’re going to change something, not destroy it. If you don’t return, your variable/value will be missed. So, keep in mind, always return in filter callback.

Another way to implement this:

add_action( ‘init’, ‘my_callback’ );

 Function my_callback(){
    // Do something.
}

In this mode, we have separated the callback function instead of using an anonymous function. There is no difference.

Hook Priority

add_action( ‘init’, ‘my_callback_early’, 9  );
add_action( ‘init’, ‘my_callback_normal’, 10 );
add_action( ‘init’, ‘my_callback_late’, 11 );

The priority determines when the callback function will be executed in relation to the other callback functions associated with a given hook.

In the above example, my_callback_early is the first function that runs when reaching the init hook. After that, the my_callback_normal will run and at the end my_callback_late.

When there are multiple registered callback functions for the same hook with the same priority, the order of registering them will be used to running callback functions.

Hook Arguments

A callback function can take some arguments. For example, the excerpt_length hook will pass the current length as a parameter. So you have access to it in your callback function.

add_filter( ‘excerpt_length’, ‘my_custom_excerpt_length’, 10, 1);

function my_custom_excerpt_length( $length ) {
  $length = 50;
  return $length;
}

In the above example, 10 is the priority of the running callback, and 1 is the number of the callback function parameters. Because both of them are like default values, you can avoid writing them. The following code does exactly the same thing:

add_filter( ‘excerpt_length’, ‘my_custom_excerpt_length’ );

Practical Examples of WordPress Hooks

Add new admin menu and page:
function register_my_custom_menu_page() {
     add_menu_page( 'Custom menu page title', 'Custom menu label', 'manage_options', 'myplugin-settings.php', '', '
 dashicons-menu-alt3', 6 );
 }
 add_action( 'admin_menu', 'register_my_custom_menu_page' );
Change the excerpt length
function my_custom_excerpt_length( $length ) {
     return 35;
 }
 add_filter( 'excerpt_length', 'my_custom_excerpt_length', 999 );
Insert custom content after each post
function my_custom_post_footer($content) {
        if(!is_feed() && !is_home()) {
                $content.= "<p>Share your idea about this post in comments.</p>";
        }
        return $content;
}
add_filter('the_content', 'my_custom_post_footer');
Disable autosave
function my_prefix_disable_auto_save(){
    wp_deregister_script( 'autosave' );
}
add_action( 'wp_print_scripts', 'my_prefix_disable_auto_save' );
Change the login page message
function my_prefix_the_login_message( $message ) {
    if ( empty($message) ){
        return "<p>Welcome to this site. Please log in to continue</p>";
    } else {
        return $message;
    }
}
add_filter( 'login_message', 'my_prefix_the_login_message' );
Remove login error messages
function my_prefix_remove_login_errors( $error ) {
    return "Incorrect login information";
}
add_filter( 'login_errors', 'my_prefix_remove_login_errors');

Final Thoughts

Wrapping up, WordPress hooks are one of the most important concepts that allow us to develop plugins and add new custom functionality to WordPress. Again, don’t forget to return when using a filter hook ;).

In this article, we guided you through the basics of WordPress hooks, including what they are and how they work. We also gave you some examples of how they are used in code to add further functionality to your website.

In the comments section below, please share your experiences and thoughts with us!

Create Your
Dream Website with

Stay in the Loop

Sign up for our newsletter and stay up-to-date on the
latest WordPress trends, insights, and resources.

By entering your email, you agree to our Privacy policy and Terms of Services.

Share

Hector Farahani

Hector Farahani

I am Hector. A WordPress developer who tries to help people to enjoy using their WordPress sites.

3 Comments

  1. Thank you so much

  2. Proceed with the publication of further articles that are worth reading!

  3. WordPress hooks are like magic doors that let you sneak your code into specific points in WordPress without altering its core.


Add a Comment

Your email address will not be published. Required fields are marked *

×
Black Friday WordPress Deals - Artbees

Enjoy 50% OFF Artbees products, and partner deals!

– Extended! –

???? Days Remaining