WordPress hooks

When to add custom actions and filters, and how to pick arguments and priorities

Id wp-hooks Applies to pluginthememodule Status active Enforceable yes, no check yet Tags wordpresshooksactionsfilters

Custom action and filter hooks are critical to robust WordPress products.

Via do_action() and apply_filters() in PHP, developers can extend, limit and modify WordPress core and other third-party codebases running in a WordPress environment.

Naming conventions for these hooks are covered in hook naming.

Code that should often have a custom filter

Code that should often have a custom action

More than one variable? Use a single array argument

WordPress supports more than one attribute in hooks, however remembering the order of these positional arguments can get challenging even with good inline and supporting documentation. So if there’s more than one piece of data, we prefer an associative array with keys and values to multiple positional arguments, so we only need to remember keys, not order.

Hook priority for execution timing

WordPress uses an integer-based priority system with the default being 10. Most core uses max out at 100.

It’s frowned upon to use anonymous methods or closures in hook callbacks

Anonymous functions defeat the purpose of hooks in that they’re a royal nuisance to remove using remove_action() or remove_filter().

Except in the rare case where the explicit intention is to make it difficult to remove a hook, callbacks should always be a named function or class that can be declared in other codebases for removal.

Hook diagnostic

The list of available WordPress actions can vary by site because third-party plugins can add their own. Hooks are executed in a runtime sequence. Not all hooks are available to plugins and themes, some hooks are WordPress Admin-only, some hooks have dynamic names, etc.

Best practice is to use a developer tool like Query Monitor to inspect available hooks and attached methods. If code isn’t executing, Query Monitor can tell you with certainty if it is getting registered.

If you’re troubleshooting hooks make sure: