Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 68 ยท Hooks: Actions and Filters

Actions and Filters

Learn the hook system behind every WordPress theme and plugin - add_action, do_action, add_filter, apply_filters, callbacks, arguments and return values.

Almost everything in WordPress is extensible through one idea: hooks. Core code, themes and plugins announce "something is happening here" at many points. Other code can attach functions to those points, so it can run extra code or change a value without anyone editing core files. That is how a plugin adds a tracking script to the footer, how a theme shortens excerpts, and how WooCommerce changes the checkout without forking WordPress.

There are two kinds of hooks. Actions let you run code at a certain moment. Filters let you change a piece of data on its way through. In this lesson you will learn how to use both, the different kinds of callbacks, how arguments are passed, and why a filter must always return a value. The runnable example builds a small hook system in plain PHP so that you can see the mechanism for yourself; real WordPress cannot run on this site, and the WordPress code in code blocks is read-only.

Hooks are used in every lesson that follows. You should be comfortable with PHP functions and closures; see Anonymous Functions and Closures if you need a refresher.

The hook idea

Think of a hook as a named socket in the code. The name is just a string, for example wp_footer or the_title. Core code fires the hook; your code attaches a callback to that name.

flowchart LR
    A["Core code reaches a point<br/>do_action('wp_footer')"] --> B["WordPress looks up<br/>callbacks stored for 'wp_footer'"]
    B --> C["Callback 1 runs"]
    B --> D["Callback 2 runs"]
    C --> E["Core continues"]
    D --> E

A hook is a named list of callbacks. Firing the hook runs the list.

If nothing is attached, firing the hook does nothing and costs almost nothing, so core can offer thousands of hooks safely.

Actions: do something at a moment

An action is a notification. Attach a callback with add_action():

PHP
function mytheme_print_banner(): void {
    echo '<p class="banner">Free shipping this week</p>';
}
add_action( 'wp_footer', 'mytheme_print_banner' );

Somewhere in core (in wp_footer(), which your theme calls), this line runs:

PHP
do_action( 'wp_footer' );

That call runs every callback attached to wp_footer. Actions do not return anything useful; what matters is the side effect, such as printing HTML, saving data or sending an email.

Actions can pass arguments to callbacks. For example, save_post tells you which post was saved:

PHP
function mytheme_after_save( int $post_id, WP_Post $post, bool $update ): void {
    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }
    error_log( "Saved post {$post_id} ({$post->post_title})" );
}
add_action( 'save_post', 'mytheme_after_save', 10, 3 );

The last two numbers in add_action() are the priority (10 is the default; lower numbers run earlier) and the number of accepted arguments. Priorities get their own lesson next; this lesson uses the default.

Filters: change a value

A filter passes a value through callbacks and returns the result. Attach with add_filter(), and read the result where core calls apply_filters():

PHP
function mytheme_shorter_excerpt( int $length ): int {
    return 20;
}
add_filter( 'excerpt_length', 'mytheme_shorter_excerpt' );

Core code (simplified) looks like this:

PHP
$length = apply_filters( 'excerpt_length', 55 );

Core starts with 55. Your callback receives 55 and returns 20. If several callbacks are attached, each one receives the previous callback's return value, so they form a chain. The final value is what apply_filters() returns and what core uses.

A filter must return a value

This is the most common beginner bug. A filter callback that forgets to return makes the value null:

PHP
// Wrong: the title disappears.
add_filter( 'the_title', function ( string $title ): void {
    $title . ' (new)';
} );

// Right: always return the value, even when you do not change it.
add_filter( 'the_title', function ( string $title ): string {
    return $title . ' (new)';
} );

The second version also shows a pattern worth remembering: add return types, and handle the case where the filter should leave the value alone by returning the incoming value unchanged. If your filter only applies to certain pages or posts, check the condition inside the callback and return $value; at the end for all other cases.

Actions versus filters

Action Filter
Fire with do_action() apply_filters()
Purpose Run code at a point Modify a value
Return value Ignored Required, and it becomes the value
First argument of the callback The first piece of context (if any) The value being filtered
Typical use Print, save, send Change text, settings, arrays

Internally, WordPress stores both in the same structure. add_action() is a thin wrapper around add_filter(), and the two differ in what the firing function does with the callbacks' return values. This also means that you should never use the same hook name for both an action and a filter.

What can be a callback

A callback is anything PHP can call. All of these forms work with hooks:

PHP
// 1. A named function (pass its name as a string)
add_action( 'init', 'mytheme_register_things' );

// 2. A closure (an anonymous function)
add_action( 'init', function (): void {
    // ...
} );

// 3. A static method
add_action( 'init', [ 'Mytheme_Setup', 'register' ] );
add_action( 'init', 'Mytheme_Setup::register' );

// 4. An instance method
$plugin = new Mytheme_Plugin();
add_action( 'init', [ $plugin, 'register' ] );

// 5. A method from inside a class
add_action( 'init', [ $this, 'register' ] );
add_action( 'init', $this->register( ... ) ); // first-class callable syntax

Closures are quick, but they have a disadvantage: you cannot remove them later, because you have no name or reference to pass to remove_action(). For code that others may want to unhook, use named functions or methods. That topic is covered in a later lesson.

When you use a named function, give it a unique prefix (mytheme_, acme_). All functions in PHP share one global namespace, and a clash causes a fatal error.

Accepted arguments

do_action() and apply_filters() can pass several values. A callback only receives as many as it registered for. By default that is one:

PHP
// Core fires the filter with a value plus extra context:
$title = apply_filters( 'the_title', $title, $post_id );

// Your callback must ask for both:
add_filter( 'the_title', function ( string $title, int $post_id ): string {
    return $post_id === 42 ? strtoupper( $title ) : $title;
}, 10, 2 );

The fourth parameter of add_filter() (here 2) is the number of accepted arguments. If you leave it at the default of 1 but your callback requires two parameters, PHP throws an ArgumentCountError, because WordPress only passed one. The reverse is harmless: if your callback declares fewer parameters than are passed, PHP ignores the extras.

A hook system you can run

Real WordPress implements hooks in the WP_Hook class. The stand-in below keeps the essentials: callbacks stored by hook name, add_action and add_filter, do_action and apply_filters, argument slicing, and the chain behavior of filters. It leaves out priorities and removal on purpose; those come in the next lesson.

PHP A mini hook system: add_action, add_filter, do_action, apply_filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the output from top to bottom. The two footer callbacks run in the order they were attached. save_post receives two arguments because it registered for two. The title filter first trims, then capitalizes, then (only for post 42) appends a label, because each callback receives the previous result. An unused filter returns the original 55. The broken filter returns null, which is what a missing return produces. The last case throws, because the callback needed two arguments while only one was allowed through.

In real WordPress, a callback with no return yields null in the same way. If another callback later in the chain declares a string parameter, that null can then cause a TypeError, so a single forgotten return can break unrelated code.

Common mistakes

  • Forgetting to return in a filter. The value becomes null and the page loses content.
  • Echoing in a filter. A filter should return data. Printing from a filter puts text in the wrong place, usually before the page header.
  • Wrong accepted_args. If you need the second or third parameter, say so in the fourth argument of add_filter().
  • Hooking too early. Some functions (such as is_single()) only work after the main query runs, so attach to a hook that fires later.
  • Anonymous functions you cannot remove. Use named functions for hooks others may need to unhook.
  • Using action and filter interchangeably. If core offers do_action( 'x' ), attach with add_action(). If it offers apply_filters( 'x', $value ), use add_filter() and return a value.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between an action and a filter?

    An action is a notification where the return value is ignored. A filter passes a value through callbacks and uses what comes back.
  2. 2. A filter callback changes the title but has no return statement. What does apply_filters() give back?

    Without return, a PHP function returns null, and null becomes the new value in the chain. Always return the value.
  3. 3. A hook passes two arguments and your callback declares two parameters. What do you need to add to add_filter()?

    The default is one accepted argument. Ask for two with add_filter( $hook, $callback, 10, 2 ), or PHP throws an ArgumentCountError.
  4. 4. Why is a closure a poor choice for a hook that others might want to remove?

    To remove a hook you must pass the same callback. A named function or a method on an accessible object can be referenced; an inline closure usually cannot.
  5. 5. When several filters are attached to the same hook, what does each callback receive?

    Filters form a chain. The first callback gets the original value, each next callback gets the previous result, and the last result is returned.

Summary

  • Hooks are named points where core, themes and plugins can attach code without editing each other's files.
  • Actions (add_action, do_action) run code at a moment; their return values are ignored.
  • Filters (add_filter, apply_filters) change a value; every callback must return a value, and callbacks chain.
  • A callback can be a function name, a closure, a static or instance method, or a first-class callable.
  • Callbacks receive only as many arguments as accepted_args allows (default 1); asking for more than that causes an ArgumentCountError.
  • Prefix function names, avoid echoing in filters, and prefer named callbacks for anything others may need to remove.

Next, control the order of callbacks and learn to unhook them in Priorities, Order and Removing Hooks.