Callables, Closures and Hooks

Choose the right callable for add_action() and add_filter(), and never ship a callback that nobody can remove.

A closure on a hook is a callback nobody can unhook. Another developer needs to turn off your filter, and remove_filter() does nothing. This module covers every callable form WordPress accepts and what each choice means for the people who extend your code.

CoursePHP for WordPress Developers · Module 3 of 9 · Stage 1 "Language"
LearnAll callable forms in hooks, use and $this in closures, priorities and accepted_args
HowShort lessons with code from real plugins, IDE practice in the browser, interview questions after every lesson

The idea in one picture

flowchart LR
  A["add_action()"] --> S["string<br/>'my_func'"]
  A --> M["array<br/>[$this, 'method']"]
  A --> C["closure<br/>function () {}"]
  S --> R["remove_action() works"]
  M --> R
  C --> X["no reference:<br/>cannot remove"]
  classDef step fill:#f5f3ff,stroke:#777BB4,color:#1e1b4b
  classDef key fill:#777BB4,stroke:#4f5b93,color:#ffffff

The callable you pass decides whether anyone can remove it later.

Before → after

BeforeAfter Module 3
Anonymous closures on public hooksNamed callables that other code can unhook
A filter receives one argument instead of threeaccepted_args set right
Hooks fire in the wrong orderPriorities chosen on purpose
$this captured by accidentStatic closures where $this is not needed

You'll be able to answer

  • Which callable forms does add_action() accept?
  • Why can't you remove an anonymous closure with remove_action()?
  • What do priority and accepted_args do?