Quantcast
Channel: David B Hayes Authored WordPress Content
Viewing all articles
Browse latest Browse all 301

WordPress Hooks, Actions, and Filters: What They Do and How They Work

$
0
0

Hooks are one of the most important ideas in WordPress development.

Today we’re covering one of the most important ideas in WordPress plugin and theme development: hooks. If you’ve felt a little bewildered by this piece of WordPress—”hooks, actions, and filters”—then today is absolutely your day!

Understanding hooks isn’t all that easy, partly because the terms themselves are rather tricky to visualize and distinguish from one another.

But the payoff is huge: as a developer, I find that working with filters and actions is probably the most common way I interact with WordPress. And over time, it’s become one of my favorite things to do in WordPress, as well.

Terminology

Particularly in this case, understanding terms is half the battle. (The WordPress Codex uses all three terms very casually and inconsistently; we won’t be diving down that rabbit hole, but suffice it to say that the definitions used here are the most common ones you’ll find in WordPress generally.)

Let’s start to define our terms:

The Plugin API: The API for Hooks

WordPress’s name for our topic is the Plugin API, but I would have preferred “Hooks API.” Hooks (not plugins) are the dominant concept that we need to understand to make WordPress actions and filters work for us.

One does indeed use hooks all the time in plugin development; but hooks are also extremely useful in theme (not just plugin) development, typically through a theme’s functions.php file.

So between us, let’s privately call the “hooks, actions, filters” piece of WordPress the “Hooks API,” and move on.

How Hook, Action, and Filter Relate

This is just to get started; don’t worry if this doesn’t make total sense at the moment:

  • Actions and filters are both types of hooks.
  • Hooks come in two types: action hooks and filter hooks.
  • In WordPress, actions is another name for action hooks. Similarly, filters is another name for filter hooks.

Good so far? Don’t worry either way, and let’s move on. (At the end, you may want to come back and see if the above makes more sense.)

WordPress and Hooks: A Simple Analogy

WordPress is a factory that manufactures webpages.

To explain hooks, we will think of WordPress as a big factory. The factory kicks on whenever a visitor browses to your site, and manufactures the specific webpage they’ve asked for. This webpage has the contents of one or more posts, as well as a header, footer, sidebar, and so on.

Factory |WordPress hooks

A great analogy; drink it in

By the way, “WordPress as a factory” is probably the best analogy there is for how WordPress works in general—because it’s almost a literal description of how WordPress actually works, except with digital factory equipment (PHP files) and raw materials (database contents) rather than physical ones.

Hooks: How the WordPress Factory Calls on Outside Contractors

Actions and filters are how WordPress calls on the “outside contractors” that help it do its work.

We can think of custom code (including code from both functions.php theme functions and WordPress plugins) as outside contractors that help the WordPress factory do its webpage assembly work. Hooks—both action hooks and filter hooks—are how WordPress calls on these outside contractors.

Why WordPress Needs Outside Contractors

The core WordPress software (“WordPress core,” the software you download from WordPress.org) is a rather simple factory. There’s also a lot it can’t do by default: everything from “display today’s date at the top of every page” to “create e-commerce product pages, complete with price, shipping, and payment information.”

WordPress can handle these special orders, but to do so it needs outside contractors. This is where functions.php; other custom code; and, most commonly, plugins come into play.

How WordPress Calls on its Contractors

Hooks are how WordPress checks for outside contractors, and invites them into the factory.

Our contractors don’t have a permanent place in the factory (WordPress core). They’re stuck in the lobby until they’re invited in by one of the factory’s regular workers.

Hooks are how the regular workers in this WordPress factory check for, and invite in, any contractors that may be needed.

We can think of WordPress “hooks,” literally, as many hooks hanging in the lobby, where contractors hang notes for the regular worker. Each hook is labeled with a specific name, such as wp_head, corresponding to a part of the WordPress factory’s process (in the case of wp_head, the process of building the page’s HTML <head> section).

When a contractor wants to be part of a hook’s process, she attaches a note that says, “Excuse me, but I’d like to participate in your process. Please come get me before you begin.” Before starting this process, the regular worker checks the corresponding hook. If there’s a note on the hook, the worker goes and fetches the outside contractor who wants to participate—and lets her jump into the WordPress production process and make whatever changes she wants.

It’s worth remembering that if the contractor had forgotten to put her request on the proper hook, she’d be sitting in the lobby doing nothing during the process. If contractors don’t leave a note, they won’t be invited in by a regular worker, and they can’t do anything.

Two Kinds of Hooks, Two Kinds of Contractors

We’re halfway to understanding hooks, actions, and filters. The other part is a bit more specific: the lobby has two kind of hooks, action hooks and filter hooks.

Two workers: WordPress actions and filters

Action Hooks

The Action hooks tend to get dangled at milestones—like “you’re almost done building the page’s <head> section (wp_head)” or “you’re almost done building the page’s <body> section (wp_footer).” When contractors get invited in after hanging notes on action hooks, they tend to do just about anything they want: add a bunch of stuff to the page, or do completely other things like log an error or even send an email.

Filter Hooks and Filters

The Filter hooks work a bit differently. Contractors who hung their notes on action hooks can do whatever they want, and have no responsibility to anyone. But contractors who used filter hooks actually insert themselves in the normal worker’s process: they’re handling something — say a block of text — and have to give that same block of text (slightly modified, probably) back to the regular worker, via a PHP return statement.

So a contractor using a filter hook generally doesn’t just do whatever she wants; she works with the piece of work that her designated regular worker passes to her. “I work on the post title,” the regular worker might say. “Do whatever you want to the post title, but if you don’t hand me back the post title after you’ve made your changes, this whole process will stop cold.”

What Are These Contractors?

Our “contractors” are specialized PHP functions.

I hope we’re making sense so far; now we’re going to get a bit more technical so you can actually start writing these things. The contractors (both those hooked to Actions and those hooked to Filters) are specialized PHP functions.

Let’s look at one of each.

Example Use of a Filter Hook

Our first contractor hooks into a filter.

function wpshout_filter_example($title) {
	return 'Hooked: '.$title;
}
add_filter('the_title', 'wpshout_filter_example');

Here’s what to know about the code above:

  • Our contractor—the code that hooks into our filter—is a PHP function, hence the function { }.
  • wpshout_filter_example is the name of the contractor function.
  • ($title) is the function’s single argument. It’s what the regular worker (WordPress core) passes to the contractor to work on.
  • return 'Hooked: '.$title; is the work the function does. It adds the word “Hooked: ” to the title it was passed, and gives it back to the regular worker.
  • return is very important: it’s how the function gives back its work to the regular worker. That line is perhaps best read right-to-left: it says: “Take the regular title and add ‘Hooked: ‘ before it, then pass it back.”
  • add_filter('the_title', 'wpshout_filter_example'); is very important: it’s how you add functions to filter hooks! This merits its own bulleted list.

Here’s how to understand that last line:

  • add_filter( ); is a WordPress function. Using our factory analogy, it says: “Hang a particular contractor’s request on an individual filter hook.”
  • 'the_title' is the name of the filter hook that we’re hanging our request on.
  • 'wpshout_filter_example' is the name of the contractor: in other words, the name of the PHP function we’ve written, and that we want to work on the filter hook (in this case, the_title) that we’ve specified.

So the function wpshout_filter_example hooks onto the filter (or filter hook) the_title. When it does, it simply adds “Hooked: ” to the title, and returns it back. Make sense?

Example Use of an Action Hook

function wpshout_action_example() {
	echo "WPShout was here.";
}
add_action('wp_footer', 'wpshout_action_example');

If you’ve understood the filter example above, you’ll understand almost everything about this action example:

  • function wpshout_action_example() {} means that this function is named wpshout_action_example() and carries no arguments.
  • echo "WPShout was here."; is what the function does. echo is a PHP command that we’ll discuss shortly.
  • add_action('wp_footer', 'wpshout_action_example'); is what hooks the wpshout_action_example function to the wp_footer action hook.

As we noted, the major difference is that the hooked function doesn’t return anything. Instead, it echos (prints) a message directly onto the page. Where will this message print? It’ll print at the very beginning of the footer section—wherever the theme author has placed the function that executes actions hooked to the wp_footer action hook.

This difference—functions attached to actions can do most anything, functions attached to filters must return modifications to what they’re given—is the main distinction between the two classes of functions, who are otherwise quite similar.

What We’ve Learned

I hope we’ve learned (thanks in part to one awesome analogy) what hooks, actions, and filters are for, and the basics of how they work.

WordPress uses actions and filters to extend what it can do—from the silly examples we showed off today, all the way up to ultra-complex plugins like WooCommerce. Specifically, WordPress is able to pull in functions that are hooked to actions and filters (or “action and filter hooks”) present at specific places in the WordPress page generation process. Functions hooked to filters modify what they’re given and hand it back via a return; functions hooked to actions can do echos and just about anything else.

There’s more to learn (we’ll get to that!), but I hope this gives you a solid foundation. If you have questions or comments about anything to do with actions, filters, and hooks, we’d love to hear them below!


Viewing all articles
Browse latest Browse all 301

Latest Images

Trending Articles



Latest Images