Skip to main content

Handlers and hooks

A handler groups the callbacks that serve one part of a plugin. Register the handler class in a module's handlers array and give its #[Handler] attribute the module's container ID. The handler's tag selects the WordPress action on which XWP-DI sets it up. Each method's tag selects the action or filter WordPress will call later. Modules and startup

Register an action and a filter​

Suppose the catalog module registers Catalog_Theme::class and its configure() method returns array( 'catalog.body_class' => 'catalog' ). This handler loads on init during frontend requests. It enqueues the WordPress Dashicons stylesheet and adds catalog to the classes returned by get_body_class().

use XWP\DI\Decorators\Action;
use XWP\DI\Decorators\Filter;
use XWP\DI\Decorators\Handler;

#[Handler( tag: 'init', container: 'catalog', context: Handler::CTX_FRONTEND )]
final class Catalog_Theme {
#[Action( tag: 'wp_enqueue_scripts' )]
public function enqueue_icons(): void {
wp_enqueue_style( 'dashicons' );
}

#[Filter(
tag: 'body_class',
invoke: Filter::INV_PROXIED,
args: 1,
params: array( 'catalog.body_class' ),
)]
public function add_body_class( array $classes, string $class ): array {
$classes[] = $class;
return $classes;
}
}

Use a public instance method for each callback. An action performs work. A filter returns the value the next filter should receive. Both decorators are repeatable, so one method can serve multiple tags that supply compatible arguments. The method priority defaults to 10. Action decorator · Filter decorator

Pass WordPress arguments and inject dependencies​

With the default INV_STANDARD, WordPress calls the handler method directly. Constructor injection works with this mode because the container creates the handler. Use INV_PROXIED when the method needs a container entry alongside WordPress arguments.

In the body_class example, WordPress can supply both the class list and the caller's additional classes. Setting args: 1 accepts only the class list. XWP-DI appends the value of catalog.body_class as the second argument. Set args explicitly when using params. Otherwise the ordinary action and filter decorators use the method's full parameter count. For a hook that supplies no arguments to the method, use args: 0.

Entry in paramsValue passed to the method
A service class name or a container entry IDThe value returned by the handler's container
'!value:catalog'The literal string catalog
'!global:post'The current $GLOBALS['post'] value, or null if absent
'!const:WP_DEBUG'The constant's value from Jetpack Constants
'!self.hook' / '!self.handler'The current hook decorator / handler decorator

Combine proxy options with bitwise OR, for example Filter::INV_PROXIED | Filter::INV_LOOPED. INV_LOOPED skips a recursive call while that callback is already running. INV_ONCE allows one invocation attempt. INV_SAFELY logs a throwable from the callback or its argument resolution and returns the incoming filter value. Invocation flags · Callback argument resolution

Choose when the handler loads​

Initialization constructs the handler and runs its optional on_initialize() method. Registering callbacks attaches the decorated methods to WordPress. Choose a strategy based on when you need each step.

Handler:: strategyWhen the handler initializesWhen callbacks attach
INIT_DEFFERED (default)On the handler's tag at its priorityImmediately after initialization on that tag
INIT_EARLYWhen the module registers the handlerOn the handler's tag
INIT_IMMEDIATELYWhen the module registers the handlerDuring the same registration call
INIT_ON_DEMANDWhen the invoker attempts to attach its first callbackOn the handler's tag
INIT_JUST_IN_TIMEWhen a registered callback first fires and the handler's conditions passOn the handler's tag, using proxies

For a deferred handler without an explicit tag, v1 uses the action currently running and schedules setup at the current priority plus one. Giving a handler a tag and priority makes the order visible. If your callback needs init at priority 10, for example, arrange for the module to register the handler before init, then set the handler's tag to init at priority 5. Both lazy strategies use proxies automatically. For an object you already constructed, xwp_load_hook_handler( $object, 'catalog' ) attaches its methods immediately. The factory uses INIT_DYNAMICALY for an existing object without a handler decorator. The constant spellings shown here are part of v1.10.0. Handler strategies · Handler factory · Registration order

Limit a handler to matching requests​

Set the handler's context to any combination of CTX_FRONTEND, CTX_ADMIN, CTX_AJAX, CTX_CRON, CTX_REST, and CTX_CLI. The default CTX_GLOBAL accepts all six. For example, Handler::CTX_ADMIN | Handler::CTX_AJAX enables a handler on both admin screens and AJAX requests. XWP-DI classifies AJAX separately from admin screens. Use XWP_Context::show() to see which context it detected. Context detection

For a more specific guard, define public static function can_initialize(): bool on the handler. Choose a setup tag where the required state is available. An admin handler inspecting get_current_screen(), for example, can initialize on current_screen. For a condition specific to one callback, use a proxied method, such as #[Filter( tag: 'the_title', conditional: 'is_singular', invoke: Filter::INV_PROXIED )]. The proxy checks the condition and method context when the hook fires. A directly registered callback on an already loaded handler bypasses that check. Handler initialization · Admin screen example

Register a family of dynamic tags​

Suppose a plugin registers book and film post types. Add this method to an admin handler to rename the Title column on both list screens. Import XWP\DI\Decorators\Dynamic_Filter alongside the other decorators.

#[Dynamic_Filter(
tag: 'manage_%s_posts_columns',
vars: array( 'book' => 'Book title', 'film' => 'Film title' ),
args: 1,
)]
public function rename_title_column( array $columns, string $label ): array {
$columns['title'] = $label;
return $columns;
}

XWP-DI registers manage_book_posts_columns and manage_film_posts_columns. Each key fills the %s placeholder, and its mapped value reaches the method as the last argument. With a list such as array( 'book', 'film' ), each value supplies both the tag fragment and the final argument. vars also accepts a zero-argument callable or a container ID that resolves to an array. Dynamic actions follow the same convention. Both decorators pass WordPress arguments first, then any params, then the mapped value. Dynamic filter · Dynamic action

For a single ordinary action or filter, modifiers: 'book' fills one %s in its tag without adding a method argument. A container placeholder such as 'save_post_{catalog.post_type}' resolves the named entry when XWP-DI reads the ordinary hook tag. Tag resolution

Trace a missing callback​

  1. After the module's startup hook, check xwp_hook_invoker()->has_handler( Catalog_Theme::class ). If it returns false, check the module's handlers list and its initialization hook.
  2. After the handler's setup hook, inspect xwp_hook_invoker()->get_hooks( Catalog_Theme::class ). Entries are grouped by method name. If the method is absent, check visibility, the handler's context, and its setup priority.
  3. If the method is present, compare its resolved tag and priority with the actual WordPress call. Check can_initialize() and the method's proxy conditions. A callback attached after its event must wait for the next occurrence.
  4. If a callback runs with an unexpected argument, inspect args, the order of params, and the invocation mode. A filter must also return the complete value expected by the next callback. Invoker inspection methods · Reference and troubleshooting