Skip to content

WordPress hooks explained: actions vs filters with examples

WordPress hooks let your own code run at set moments, or change a value before WordPress uses it. See how actions and filters differ, how priorities set the order, why a callback can silently do nothing, and where the code should live.

WordPress hooks are the points where your theme or plugin code can join in while WordPress builds a page. This article is for anyone who has pasted an add_action() or add_filter() snippet and wants to know why it works, or why it does not. Either way, your code is a callback, which is the function you hand WordPress to run for you later. There are two kinds of hook, and they behave differently. An action announces that something happened. For example, do_action( 'wp_head' ) runs every callback registered for that moment and ignores what they return. A filter passes a value along a chain. apply_filters( 'excerpt_length', 55 ) hands the number 55 to each callback in priority order and keeps whatever comes back. You register both the same way, with a hook name, a callback, a priority and a count of accepted arguments, so they are easy to mix up. The most common hook bug is a filter callback that changes a value and then forgets to return it. One timing rule explains most of the rest. A callback runs only if it was registered before its hook fired.

What you’ll accomplish

  • Read any add_action() or add_filter() call and predict whether the callback runs, when it runs, and which arguments it receives.
  • Change WordPress behaviour through a filter instead of editing core or parent-theme files that the next update overwrites.
  • Order callbacks deliberately with priorities, instead of finding collisions in production.
  • Diagnose the four ways a callback silently does nothing, and fix each one.
  • Decide where the code belongs: child theme functions.php, a must-use plugin, or a real plugin.

Prerequisites

  • A WordPress install you can edit files on — local or staging, not production for the first pass. From the install root, wp core version should print something like 6.8.2.
  • PHP errors written somewhere you can read. In wp-config.php, above the “stop editing” line:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

Reload any page, then confirm the log file exists:

tail -n 5 wp-content/debug.log

An empty file is a success signal here — it means logging is on and nothing has failed yet. A “No such file or directory” message means the constants did not take effect.

  • Somewhere to put PHP. A child theme if the code is presentation-related, or wp-content/mu-plugins/ if it must load early and survive theme switches.
  • WP-CLI, optional but used throughout to check results without loading a browser.

How it works

Every hook name is a key in the global $wp_filter array, and each value is a WP_Hook object holding the registered callbacks bucketed by priority. add_action() and add_filter() are the same function underneath — both write into $wp_filter — and do_action() and apply_filters() both walk those buckets from the lowest priority number upward, calling each callback in turn. The only real difference is what happens to the return value: apply_filters() feeds it into the next callback and finally returns it to the caller, while do_action() throws it away.

That shared machinery means registration is just a write to an array, and firing is just a read. Nothing reconciles the two. If your code writes to $wp_filter['after_setup_theme'] at a point in the request where after_setup_theme has already been read and discarded, the write succeeds, add_action() returns true, and the callback sits in memory unused until the request ends. No exception, no notice, no log line.

Vertical timeline of eight WordPress hooks from muplugins_loaded through shutdown, with a side panel showing that an add_action call for after_setup_theme made during init returns true but never executes

The second thing to internalise is the contract difference. A filter is a chain where each link is obliged to hand something on; an action is a broadcast where nobody is expected to answer. The official hooks documentation puts it plainly: an action takes what it receives, does something, and returns nothing, while a filter takes what it receives, modifies it, and returns it.

Two lanes: a filter chain where the value 55 passes through three callbacks at priorities 5, 10 and 20 and emerges as 25, and an action lane where three callbacks run and nothing is returned

Step-by-step

  1. Attach an action and prove it ran. Actions are the easier half because there is no return value to get wrong. Put this in your child theme’s functions.php:
add_action( 'init', 'sh_hook_probe' );

function sh_hook_probe() {
    error_log( 'sh_hook_probe ran on init' );
}

Load any page, then read the log:

tail -n 1 wp-content/debug.log
[07-Aug-2026 14:02:11 UTC] sh_hook_probe ran on init

That line is the success signal. If it is missing, the file you edited is not the one WordPress loads — check which theme is active before touching anything else.

  1. Attach a filter and return the value. The excerpt_length filter receives the current word count and expects a word count back:
add_filter( 'excerpt_length', 'sh_excerpt_length' );

function sh_excerpt_length( $length ) {
    return 30;
}

Ask WordPress what the filter now produces:

wp eval 'echo apply_filters( "excerpt_length", 55 ) . PHP_EOL;'
30

Getting 55 back means the callback never ran; getting an empty line means it ran and returned nothing.

  1. Use priority to control order. Priority is the third argument and defaults to 10. Lower numbers run earlier. Add a second callback that puts a ceiling on whatever the first one decided:
add_filter( 'excerpt_length', 'sh_excerpt_length', 5 );
add_filter( 'excerpt_length', 'sh_excerpt_cap', 20 );

function sh_excerpt_cap( $length ) {
    return min( $length, 25 );
}
wp eval 'echo apply_filters( "excerpt_length", 55 ) . PHP_EOL;'
25

The 25 proves the order: priority 5 returned 30, priority 20 received that 30 and capped it. Swap the two priority numbers and you get 30 instead, because the cap runs against the untouched 55.

  1. Declare accepted args when you need more than the first parameter. The fourth argument of add_filter() tells WordPress how many parameters to pass through; it defaults to 1 regardless of how many the hook offers. the_title offers two — the title and the post ID:
add_filter( 'the_title', 'sh_flag_drafts', 10, 2 );

function sh_flag_drafts( $title, $post_id ) {
    if ( 'draft' === get_post_status( $post_id ) ) {
        $title = '[Draft] ' . $title;
    }

    return $title;
}

Confirm both parameters arrive:

wp eval 'echo apply_filters( "the_title", "Test", 1 ) . PHP_EOL;'
Test

A plain Test on a published post ID is the success signal. Drop the 2 from the registration and the same command returns a fatal instead, because PHP refuses to call a two-parameter function with one argument. The add_filter reference states the rule directly: the accepted-args value must reflect the number of arguments the callback actually opted to accept.

  1. Remove a callback someone else registered. remove_action() and remove_filter() need the same hook name, the same callback identifier, and the same priority that was used to register. Removal must also happen after registration but before firing, which is why the removal itself goes inside a hook:
add_action( 'init', 'sh_unhook_generator' );

function sh_unhook_generator() {
    remove_action( 'wp_head', 'wp_generator' );
}
wp eval 'echo has_action( "wp_head", "wp_generator" ) ? "attached" : "removed", PHP_EOL;'
removed
  1. Put the code where it loads in time. Presentation tweaks belong in a child theme. Anything that has to run before themes exist — or must survive a theme switch — belongs in a must-use plugin, which WordPress loads first and cannot be deactivated from the admin:
mkdir -p wp-content/mu-plugins

Delete the sh_excerpt_length copy you added to functions.php in step 2 before creating the file below. Two definitions of the same function name is a fatal Cannot redeclare error, and the mu-plugin loads first, so the theme copy is the one that fails.

Create wp-content/mu-plugins/sh-hooks.php:

<?php
/**
 * Plugin Name: SH Hooks
 */

add_filter( 'excerpt_length', 'sh_excerpt_length', 5 );

function sh_excerpt_length( $length ) {
    return 30;
}
wp plugin list --status=must-use --field=name
sh-hooks.php

Seeing the filename listed means WordPress is loading it on every request, at muplugins_loaded, before any regular plugin or theme code exists.

Validate it works

Three checks cover almost every hook question you will have.

Did the hook fire at all? did_action() returns how many times an action has run so far in this request:

wp eval 'echo did_action( "init" ), PHP_EOL;'
1

A 0 here means you are asking before the hook fires, which is the timing problem in miniature.

What is attached, and at which priority? Read the priority buckets straight out of the WP_Hook object:

wp eval 'global $wp_filter; print_r( array_keys( (array) $wp_filter["excerpt_length"]->callbacks ) );'
Array
(
    [0] => 5
    [1] => 20
)

What happened during a real page load? The CLI cannot see a themed front-end request. Query Monitor lists every hook that fired and every callback that ran, with file and line — see the Query Monitor guide for reading its Hooks and Actions panel.

Troubleshooting

The callback was registered after the hook fired. This is the failure mode with no symptoms: add_action() returns true and nothing runs. It happens when a plugin activated at init tries to hook after_setup_theme, or when code inside a template_redirect callback tries to hook wp. Check with did_action( 'the_hook' ) at the point of registration — anything above 0 means you are too late. The fix is to move the registration earlier: to the top level of the file rather than inside another callback, or into a must-use plugin.

The callback declared more parameters than it will receive. With the default accepted args of 1, a two-parameter callback either takes a fatal ArgumentCountError or, if the extra parameters have defaults, silently receives null. That is worse, because get_post_status( null ) quietly falls back to the global post and your logic appears to work on single-post views and misbehave everywhere else. Count the parameters your function signature declares and pass that exact number as the fourth argument.

The filter callback forgot to return. A callback that modifies its value and ends without return gives WordPress null, and null is what the next callback in the chain receives and what the caller ultimately gets. Excerpts come out empty, titles vanish, option values reset to defaults, and nothing appears in the log. Every path through a filter callback — including early exits — must return something. When you decide not to change the value, return $value; unchanged.

remove_action() cannot find a closure. A callback registered as an anonymous function has no name to reference, so there is no identifier you can pass to remove_action(). If the closure is in code you control, convert it to a named function or a class method and register that instead. If it is in a third-party plugin, you cannot remove it by name — reach for the object through $wp_filter and match on the closure instance, or disable the feature through whatever setting the plugin exposes. This is the concrete reason to avoid closures for anything another developer might need to detach.

Two callbacks share a priority and fight. Callbacks at the same priority run in registration order, which depends on plugin load order, which depends on alphabetical directory names. That is not something to build on. When ordering matters, make it explicit: give the callback that must win a distinctly later priority such as 50 or 999, and give one that must set a baseline something like 1. Do not use PHP_INT_MAX — it leaves you nowhere to go when something later needs to run after yours.

When this is the wrong approach

Hooks only reach the extension points that core, the theme, or the plugin chose to expose. If no hook exists at the moment you need, the answer is not to patch core or edit the parent theme; both get overwritten on update and neither leaves a trace for the next person. Open an issue with the plugin author asking for a hook, or wrap the feature in your own code path.

Hooks are also the wrong tool for expensive work. A callback on init runs on every front-end request, every admin screen, every admin-ajax.php call and every REST request — so a remote API call in an init callback multiplies your slowest dependency across the whole site. Schedule that work with WP-Cron or an external queue and have the hook read a cached result.

Finally, if you are filtering markup at wp_head to work around something a caching layer or a CDN is doing, you are fixing the symptom one request at a time. Change the layer that produces the behaviour instead.

Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under enterprise WordPress hosting; book an infrastructure consult.