WordPress Hooks: The Essential Guide

WordPress hooks

WordPress hooks are a helpful tool designed for developers who make WordPress plugins and themes. In fact, they’re so useful that the creators of WordPress utilize them throughout WordPress core. But what exactly are WordPress hooks and how do you use them?

In this guide, we’ll take a look at how to effectively use WordPress hooks and dive into the fundamentals. Let’s dive in!

What are Hooks in WordPress?

In a nutshell, WordPress hooks are snippets of WordPress code that grab and execute snippets of other pieces of WordPress code. They essentially allow developers to jump around among various files easily in their themes and plugins.

WordPress hooks come packaged in WordPress core. Every theme and plugin utilizes them, as well.

WordPress Hooks Explained

The main purpose of hooks in WordPress is to allow developers to fundamentally change how the content management system operates without altering the WordPress core files. Because WordPress is open-source, you could mess with core files, but there’s a 99% chance you’d regret it within minutes.

Although it can be a bit difficult to understand for newer developers, it’s absolutely critical to learn how WordPress hooks work. Much of the time, confusion arises because of the terminology WordPress uses. Although the behind-the-scenes action is quite similar to that of many programming languages, the verbiage is different. It’s often easiest to learn how to create and use these by first following examples, reading about them, and then practicing.

In order to write WordPress hooks, you’ll need to be able to code in PHP. PHP is the underlying language for the vast majority of WordPress. You can think of hooks as openings that other PHP functions can latch onto. You can also think of WordPress hooks as callbacks that do something to data or the display before the user sees the data. 

Two Types of WordPress Hooks

There are two major types of WordPress hooks you’ll need to learn:

  • WordPress action hooks
  • WordPress filter hooks

Let’s take a look at these two types of WordPress hooks and how they differ. We’ll also explore a few examples of both action hooks and filter hooks to better illustrate their usage.

The Difference Between WordPress Action Hooks and Filter Hooks

If you’ve spent time reviewing the codex of WordPress, you’ve probably seen these terms casually tossed around. Unfortunately, one of the weaknesses of the codex is that it’s written by developers themselves. As a side effect, some important distinctions that may be obvious to them, aren’t obvious to those who aren’t as familiar with WordPress core code.

The easiest way to differentiate between the two types of WordPress hooks is that action hooks do not return values, while filter hooks do return values.

For those familiar with common programming languages, this is like saying that action hooks have a “void” return type, whereas filter hooks return actual data.

Filter hooks can be thought of as pre-processing hooks or events. A filter hook might filter results returned from a database query to only contain entries with the last name of “Smith.” This filter hook should be called before the actual database query is called, telling WordPress in advance that it’ll need to take out irrelevant results before returning them.

WordPress ction hooks can be thought of as retrieving something through code. A common example of an action hook is the insertion of an additional CSS file to a site page to make it appear differently. Remember, hooks change how data is displayed before it’s even delivered to the user. An action hook delivers a new CSS file that makes the user experience better. This process doesn’t involve editing WordPress’s core nor does it require editing the core web root of the site. In this way, WordPress hooks can make it much easier, in conjunction with plugins, to manage multiple WordPress sites.

Hooks and Filters Explained

Now that we’ve looked at a more abstract overview of WordPress hooks and filters, let’s dive into the more technical details of how these function.

You can think of a WordPress hook as an event that occurs with a name. An example of one contained in WordPress core is called save_post. With hooks, we essentially say that when save_post is executed, we want our hook or filter to attach and run alongside it.

We attach what are called callbacks, or callback functions, to hooks in WordPress. This is just a fancy way to say that we’re asking WordPress to run the code contained in functions we’ve created when the event is fired that we “hooked” (such as save_post in our example above).

While it’s easy enough to add WordPress hooks, as we’ll explore later, remember that one improperly written callback can completely ruin your chain of callbacks. If this occurs, one broken link in the chain of callbacks can completely ruin all of your hard work! Always do a backup before making changes. Take advantage of a trustworthy WordPress backup plugin before you make any changes. 

Interested in even more technical details behind how hooks work? Check out the next section! We have a more in-depth explanation as well as a tutorial on creating your first action hook and your first filter hook!

How Do Hooks in WordPress Work?

Remember, though there are a few differences, action hooks and filter hooks in WordPress can be seen as largely the same. Let’s briefly run through how these hooks work. We’ll go over an example and tutorial later in the article.

Both types of hooks need to be registered with WordPress before using them. This gives the CMS the list of functions to attach when there’s an event run to which we’ve “hooked” our code. Also, ensure that actions are registered as actions and filters are registered as filters.

When adding an action, take advantage of the WordPress core function add_action(). When adding filters, use the corresponding WordPress core function called add_filter(). If your callbacks (functions up the chain when your event or action is run) don’t return any data, you need to register it as an action. If it returns what WordPress refers to as filterable data, then register it as a filter.

Whatever you specify in these functions is run when your site is opened by a user. WordPress has an internal generator that puts all of these actions and filters together for us. There are also corresponding removal functions for actions and filters. These can be utilized to eliminate a function from your callback chain. They’re often contained in conditional statements in WordPress PHP.

Just like our add functions, they’re called remove_action() and remove_filter().

How Do I Create a Hook in WordPress?

The time has finally come for us to make our first hook in WordPress! Remember that creating hooks involves adding custom code that will be displayed and rendered to our site’s users.

Just note that any time we add custom code, we add some level of security risk. That’s why right now would be an ideal time to ensure that you have a WordPress security plugin you can trust installed and ready to go. This can help with peace of mind and ameliorate any potential threats to your site through custom code that might introduce new vulnerabilities.

Get the bonus content: A Guide to WordPress Security

Let’s take a look at how we can make a very simple action hook in WordPress. Then we’ll look at an example of a filter hook in the CMS.

How Do I Create an Action Hook in WordPress?

For our action example, let’s do something that nearly all WordPress developers will need to do at some point: adjust the content on the WordPress login page. The page is very generic.

For example, if you manage a WordPress site for an academic institution, they might ask you to remind students to use their campus email address to log into their WordPress portal. We could add a simple reminder under the “Username” and “Password” boxes that says “Remember to use your @myuniversity.edu email as your username” in order to reduce calls to the IT department asking for help logging in.

This, of course, would be more aligned with an action hook rather than a filter hook. That’s because a simple adjustment, such as editing the text on the main user login page, doesn’t actually return any data to filter.

First, we’ll need to figure out where exactly to hook our action. In most cases, looking at the PHP file where you want to add content can be very insightful. Taking a look at the WordPress file containing the login content, there are several action triggers. In our example of our reminder to students to use their institutional emails, you will notice the following code quite interesting in the login page’s PHP file:

do_action( 'login_footer' );

The do_action function is a WordPress core function that performs our action hook upon request. Of course, this is provided that we have registered all of the functions we want to attach to this hook.

In this case, “login_footer” is a premade hook by the WordPress team. Though it’s built-in, we can still attach our own code to it. By default, this hook loads the generic login page’s footer content. The footer would be an ideal place for our text, which is why we’re taking advantage of this page section hook.

We can add a new PHP function to our wp-login.php to get started. All we need to do is output a line of text, like so:

function add_uni_email_reminder() {

<p>Remember to use your @myuniversity.edu email as your username!< /p>

}

do_action( 'login_footer', 'add_uni_email_reminder' ); 

In this case, we have simply created a new “action” in the wp-login.php file. The function’s name of the action hook (add_uni_email_reminder), without the parameter parentheses, can be added to do_action()’s list of parameters to register it to be run when the footer is rendered next.

How Do I Create a Filter Hook in WordPress?

Now we’re on a roll! We’ve learned the basics of WordPress hooks and how to harness their power. We’ve even performed a little modification ourselves! The only major part left is to practice with filter hooks. Remember, these are hooks that return some type of data that we may filter through. These are a tad more complex than action hooks, but now that you understand the basics of hooks, it should be a bit easier.

Let’s get started with our WordPress filter hook. First, we’ll need to decide what specific filter we’d like to add. One item that your client could request is to customize the page addition functionality. This is where WordPress users can add new blog posts. To keep it as simple as possible, let’s say that we want to edit the text “Enter title here” contained in the “Title” text box. Let’s say we want to make it more specific and have it say “Enter Blog Post Title” instead.

Notice that in our filter hook example below, our function has a parameter. In addition, the actual execution of our filter has an additional “priority” parameter. You’ll also notice that the actual function we use to register our hook is the exact same as our “action” example, add_action. The way we can tell that this function is a filter hook rather than an action hook is that when it’s actually run, the function executed as we can see in the WordPress core code is apply_filters( ‘enter_title_here’, __( ‘Enter title here’ ), $post );. We’re applying filters as the function’s name strongly suggests.

This is often a tripping point for newer users. It’s really just a slight wording issue; once you get past that, deciphering the difference between hooks and filters in WordPress becomes quite simple! Without further adieu, let’s dive into changing that placeholder text!

function our_new_title_here( $title ) {

$title = __( 'Enter Blog Post Title', 'text-domain' );

return $title;

}

add_action( 'enter_title_here', 'our_new_title_here', 10 );

You may be wondering what that “10” means in our add_action function. Hopefully, you understand the first two parameters; the first is the default WordPress hook, and the second is the name of the function and filter we are attaching to enter_title_here. The “10” is the level of priority we’re assigning to this filter.

Remember, both actions and filters in WordPress are a series of cascading “callbacks” or custom functions that are run. These are given different priority levels. We’ll explore what different numbers mean, what acceptable parameters are, etc., a bit later on. However, it’s important to understand that 10 is the WordPress default “normal” priority level for filters and actions for now.

Where Are WordPress Hooks Stored?

You may be wondering where WordPress could possibly store all of these actions and filters. We’ve referenced the WordPress core, but this is simply the location of built-in actions and filters and the functions attached to them. Seasoned WordPress users likely know that these hooks are not stored in any of the databases created when WordPress is installed.

One of the most unique features of actions and filters in WordPress is that they aren’t really “stored” anywhere! Once we have added an action or filter, that action or filter can be accessed globally throughout our WordPress site. If you think there’s no possible way that it’s stored nowhere, you’re correct!

Though the structure is fairly complex, there is one PHP variable where all of our actions and filters are stored. This variable is global and called $wp_filter. Do not mess with this variable directly!

For those interested in the technical details, this variable $wp_filter is a PHP array. It holds a large series of objects that are of the type WP_HOOK. Within the PHP file you can read in wp-includes/class-wp-hook.php, there’s one important method: this->apply_filters(). This method is what fires off all our callbacks and “registers” our custom filters and hooks. It’s essentially the bread and butter of WordPress hooks.

In order to fully take advantage of this awesome feature of WordPress, we’ll need to know some of the most common WordPress hoooks. Look no further than our cheatsheet below!

WordPress Hooks List: WordPress Hooks Cheatsheet

Let’s start out with a small dose of realism: there’s no possible way we could go over every single hook in WordPress. Thankfully, some researchers have compiled a list of (literally) every single action and filter, for those who are curious. You can see a full list of all WordPress hooks here, but be careful to look at security warnings regarding each hook. You should not utilize any that are labeled as “deprecated”. This means that they may or may not be supported in the most modern version of WordPress, but either way, they soon will not be supported.

In all likelihood, 90% of the time, you’ll only be interested in a few WordPress hooks. Here are five of the most popular actions and filters in WordPress, along with a brief explanation of what they are!

  1. add_setting() – Just as its name suggests, this action adds to your WordPress settings. You probably won’t want to include this action on any user-facing page, but it can be a lifesaver if you’re modifying administrative pages.
  2. apply_filters() – Does this one look familiar? It should, because we used it earlier! This immediately calls our whole chain of callbacks associated with a hook.
  3. esc_attr() – The name of this one is shorthand for “escape HTML attributes”. Escaping HTML means that we use ASCII codes for HTML symbols. This is almost universally used to “sanitize input” to pages. In other words, this action would be highly desirable to attach to a hook run when a user submits a form. It prevents users from attacking your site with cross-site scripting attacks in particular.
  4. the_content() – This hook’s name probably sounds simple, because it is! It simply grabs the content of the current post being viewed. This is ideal if you’re allowing users to export the contents of a post. For example, some sites offer Premium users the ability to export any article as a PDF file.
  5. wp_nav_menu() – Shorthand for “WordPress Navigation Menu”, this hook is an action hook. It’s utilized to simply display the main navigation menu you create when you first make your WordPress site. This is great if you have pages that have a significantly different layout and wish to display your menu in an alternative area.

In What Order do WordPress Hooks Run? The WordPress Hooks Firing Sequence

Unfortunately, the exact order that WordPress hooks run isn’t as apparent as you might imagine. This is due to the sheer volume of hooks. One researcher performed an advanced analysis of this to count the number of hooks running and the order in which they were run when the home page of a WordPress site was visited.

As though this wasn’t complex enough, some WordPress hooks have hooks attached to them of various priorities! You can take a look at the hundreds of hooks run and their orders on this post about the WordPress hooks firing sequence. Just note: you should not attempt to run this analysis on anything but a test server where you can afford to lose everything!

While we can’t do much about the order of default hooks, we can do something about the order of hooks that we specify. This is where the priority of hooks comes in. We alluded to it earlier.

How Does Priority in WordPress Hooks Work?

As we mentioned, the default priority level assigned to a hook by WordPress is “10”. Whatever you decide to make the priority, remember that the value must be a positive integer. This means that, unfortunately, “0” isn’t a valid value. Also, -100 wouldn’t be valid, and 0.5 wouldn’t be valid. However, 1 would work, as would 1111.

In general, the smaller the integer, the lower the priority. If you want a hook to run after a hook you assigned the default value of 10, for example, you could make its priority a 9. Your very lowest-priority hook can be given a 1. Additionally, WordPress hooks can be assigned the same priority. This is if you don’t care what order they run in.

Wrapping Up: Hooks in WordPress

One of the biggest stumbling blocks for new WordPress developers is how non-standardized much of this information can be. While you’ll find plenty of technical blogs, many cover narrow topics, and they can be difficult to aggregate.

The best way is to begin experimenting with WordPress action hooks and filter hooks on your site. Once you’ve made more complex WordPress hooks, you’ll need to learn the hooks that you tend to use more often. Over time, you’ll memorize these hooks. It’s an arduous process, and nobody is capable of memorizing every one of these hooks.

The WordPress codex is the single best resource to utilize on your journey to be the world’s next top WordPress developer.

WordPress hooks

Keep reading the article at WordPress News and Updates from iThemes – iThemes. The article was originally written by Kristen Wright on 2021-01-25 12:36:58.

The article was hand-picked and curated for you by the Editorial Team of WP Archives.

Disclosure: Some of the links in this post are "affiliate links." This means if you click on the link and purchase the product, We may receive an affiliate commission.

Leave a Comment

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

Show Your ❤️ Love! Like Us
Scroll to Top