Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 68 ยท Hooks: Actions and Filters

Creating Your Own Hooks

Learn to add extension points to your plugin or theme with do_action and apply_filters - naming, prefixes, context arguments, documentation, deprecation and testing.

So far you have used hooks that WordPress core fires. The same mechanism is open to you: any plugin or theme can call do_action() and apply_filters() at points of its own choosing. Other developers (or you, a year from now) can then change the behavior without editing your files, which is the whole point of an extensible plugin.

Adding a hook is easy; adding a good one takes some care. A hook becomes part of your public interface the moment someone depends on it, so its name, its arguments and the type of value a filter accepts all need to be chosen on purpose. This lesson shows how to pick extension points, name them safely, document them, retire them, and test them. It builds on Actions and Filters and Priorities, Order and Removing Hooks.

Action or filter?

Choose the type by what you want other code to be able to do:

You want others to... Use Example
Run extra code at a moment in time do_action() "A form was submitted"
Change a value before you use it apply_filters() "The subject line of the email"
Veto or skip something a filter returning a boolean "Should this order be exported?"

An action says "this just happened" or "this is about to happen". It does not return anything. A filter says "here is my default; do you want something else?" and it returns the final value, which your code then uses.

PHP
// An action: announce an event.
do_action( 'acme_newsletter_after_send', $sent_addresses, $campaign_id );

// A filter: offer a value, use whatever comes back.
$subject = apply_filters( 'acme_newsletter_subject', $subject, $campaign_id );

Naming hooks

Hook names live in one global namespace shared by WordPress core and every active plugin. Follow these rules:

  • Prefix with your plugin or theme slug: acme_newsletter_subject, not subject. A bare name can collide with another plugin's hook, and then both plugins' callbacks run for both.
  • Use lowercase letters, digits and underscores.
  • Describe the moment or the value: _before_send, _after_send, _subject, _recipient.
  • Do not name a hook after an implementation detail that might change.
  • Avoid dynamic parts unless they add real value. A name like "acme_newsletter_{$type}_sent" lets people target one kind of campaign, but it cannot be found by searching the code for the full name. If you build names dynamically, document the dynamic part.

Core follows the same style; you will recognize save_post_{$post_type} as a dynamic hook.

Pass context, not just the value

Filters are far more useful when they receive the information needed to decide. Compare these two designs:

PHP
// Weak: a callback only sees the subject text.
$subject = apply_filters( 'acme_newsletter_subject', $subject );

// Better: it also receives the campaign and the audience.
$subject = apply_filters( 'acme_newsletter_subject', $subject, $campaign, $subscribers );

Callbacks opt in to the extra arguments with accepted_args, as you saw before. Adding more arguments at the end later is backward compatible, because existing callbacks only receive the number they asked for. Removing or reordering arguments breaks everyone, so decide the order carefully up front.

Also validate what a filter returns. Filters are third-party code: someone may return null or an array by mistake. Cast, check the type and fall back to your default when the result is unusable.

do_action_ref_array and the _ref_array filters

do_action_ref_array( $hook, $args ) and apply_filters_ref_array( $hook, $args ) take all arguments as a single array instead of a variable argument list. Before PHP passed objects as handles, this was the way to hand callbacks a variable by reference, for example do_action_ref_array( 'pre_get_posts', array( &$this ) ) inside WP_Query. In modern plugin code you rarely need it: do_action( 'my_hook', $a, $b ) is equivalent for ordinary values. It is still handy when the arguments already live in an array, and it is also the function core uses internally for the deprecated-hook helpers below.

Document every hook

Unlike a function, a hook has no signature in the code, so documentation is the only way anyone learns what arguments it passes. WordPress core uses a docblock directly above the call:

PHP
/**
 * Filters the subject line of a newsletter before it is sent.
 *
 * @since 1.2.0
 *
 * @param string   $subject     The subject line.
 * @param Campaign $campaign    The campaign being sent.
 * @param string[] $subscribers Email addresses that will receive it.
 */
$subject = apply_filters( 'acme_newsletter_subject', $subject, $campaign, $subscribers );

State what the hook does, since which version it exists, and the type and meaning of each argument. For actions, say when exactly they fire ("after the last email was handed to the mailer"). For dynamic hook names, add a sentence such as "The dynamic portion of the hook name, $type, refers to the campaign type".

A plugin with its own extension points

Here is a stand-in newsletter plugin with four extension points: a filter for the subject, a filter that can skip a recipient, and two actions around the send. The hook functions are a compact stand-in for WordPress's, and the "add-on" at the bottom plays the part of a second plugin.

PHP A newsletter plugin and its add-on

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.

The plugin never mentions the add-on, yet the add-on changed the subject, skipped one address and logged the result. Two details are worth copying into real code. The plugin only accepts the filtered subject if it is a non-empty string, and it only sends when should_send is exactly true, so a buggy callback that returns null cannot silently turn into "send".

flowchart TD
    A["send( subscribers, subject )"] --> B["apply_filters<br/>acme_newsletter_subject"]
    B --> C["do_action<br/>acme_newsletter_before_send"]
    C --> D{"For each subscriber"}
    D --> E["apply_filters<br/>acme_newsletter_should_send"]
    E -->|"true"| F["Add to sent list"]
    E -->|"anything else"| G["do_action<br/>acme_newsletter_skipped"]
    F --> D
    G --> D
    D -->|"done"| H["do_action<br/>acme_newsletter_after_send"]

Each extension point is a place where other plugins can step in without touching the newsletter code.

Deprecating and renaming hooks

Sooner or later you will want to rename a hook or change its arguments. Do not just delete the old name: sites that still use it would stop working without any message. WordPress provides two helpers that fire the old hook for backward compatibility and warn developers:

PHP
// The old name still works, but callbacks trigger a deprecation notice.
$subject = apply_filters_deprecated(
    'acme_subject',                                  // old hook name
    array( $subject, $subscribers ),                 // arguments, as an array
    '2.0.0',                                         // version it was deprecated in
    'acme_newsletter_subject'                        // replacement
);

do_action_deprecated( 'acme_sent', array( $sent ), '2.0.0', 'acme_newsletter_after_send' );

Both functions only do something when a callback is registered on the old hook: they fire it and report the deprecation (the notice is shown when WP_DEBUG is on). If nothing listens, they cost almost nothing. You then call the new hook as usual. Keep the old one for at least a few releases and say so in your changelog.

Testing hook behavior

Hooks are behavior, so they deserve tests. Test three things: that your code fires the hook with the arguments you documented, that a filter's result is really used, and that bad filter output is handled. WordPress's PHPUnit test case backs up and restores the global hook state between tests, so callbacks registered in one test do not leak into the next. In the stand-in below, a helper resets the registry for the same reason.

PHP Deprecated hooks and hook tests

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.

Test 4 prints a deprecation line before its PASS, and test 5 prints no notice because nothing was hooked on the old name. That mirrors the real helpers, which stay quiet unless somebody is still using the deprecated hook.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should you prefix your own hook names, for example acme_newsletter_subject instead of subject?

    Every plugin and core share the same hook namespace. A generic name can make unrelated callbacks run for your hook, and yours for theirs.
  2. 2. You want other plugins to be able to change the subject line your plugin sends. Which call fits?

    A filter lets others change a value and you use what comes back, so you assign the return value of apply_filters(). do_action() does not return anything.
  3. 3. After a filter runs, your code expects a string. What is the safest approach?

    Filter callbacks are third-party code and can return the wrong type. Validate the result and fall back to the default instead of passing bad data on.
  4. 4. You rename a hook in version 2.0. What should you do with the old name?

    The deprecated helpers still run old callbacks and report that the name is outdated, so existing sites keep working while developers learn about the replacement.
  5. 5. Which change to a documented filter is backward compatible?

    Callbacks only receive as many arguments as they requested, so a new trailing argument does not affect them. The other changes break existing callbacks.

Summary

  • Use actions to announce events and filters to let others change values or veto a step.
  • Prefix every hook with your plugin slug, use lowercase and underscores, and be careful with dynamic names.
  • Pass context arguments, add new ones only at the end, and validate whatever a filter returns.
  • do_action_ref_array() and apply_filters_ref_array() take their arguments as one array; ordinary code can use the regular functions.
  • Document each hook with a docblock: description, @since, and every @param.
  • Retire hooks with apply_filters_deprecated() and do_action_deprecated(), and test that your hooks fire with the arguments you promised.

Next, meet the hooks that WordPress itself fires during a request: Core Hooks You Will Use.