@wordpress/hooks package provides a lightweight event management system for JavaScript, similar to WordPress PHP hooks. It enables extensibility through actions and filters.
Installation
Core Concepts
Actions
Actions allow you to execute code at specific points without returning a value.Filters
Filters allow you to modify data before it’s used.Basic Usage
Global Hooks
In WordPress, hooks are available globally:Custom Hook Instance
Actions
addAction
Registers a callback to be executed when an action fires.hookName(string) - Name of the actionnamespace(string) - Unique identifier (vendor/plugin/function)callback(Function) - Function to executepriority(number) - Optional priority (default: 10)
doAction
Triggers all callbacks registered to an action.removeAction
Removes a previously registered action callback.removeAllActions
Removes all callbacks for an action.hasAction
Checks if any callbacks are registered for an action.doingAction
Checks if an action is currently being executed.didAction
Returns the number of times an action has been triggered.Filters
addFilter
Registers a callback to modify a value.applyFilters
Applies all filters and returns the modified value.removeFilter
Removes a previously registered filter callback.removeAllFilters
Removes all callbacks for a filter.hasFilter
Checks if any callbacks are registered for a filter.doingFilter
Checks if a filter is currently being applied.didFilter
Returns the number of times a filter has been applied.Async Operations
doActionAsync
Triggers action callbacks asynchronously.applyFiltersAsync
Applies filters asynchronously.Practical Examples
Plugin Initialization
Modifying Data
Block Editor Extensions
Priority Management
Hook Events
The hooks system triggers meta events:hookAdded
Fired when a hook is added.hookRemoved
Fired when a hook is removed.The ‘all’ Hook (Development Only)
In non-minified builds, you can hook into all actions/filters:Naming Conventions
Hook Names
- Use only letters, numbers, dashes, periods, and underscores
- Don’t start with
__(reserved) - Use descriptive, hierarchical names
editor.blockInsertedform.validate.emailapp.init.complete
Namespaces
- Format:
vendor/plugin/function - Use only letters, numbers, dashes, periods, underscores, and slashes
- Must be unique
myCompany/myPlugin/logActionwordpress/editor/modifyBlockacme-corp/analytics/trackEvent
Best Practices
- Always use namespaces - Prevents conflicts with other plugins
- Choose descriptive hook names - Make purpose clear
- Document your hooks - Help other developers extend your code
- Use appropriate priorities - Control execution order
- Clean up hooks - Remove hooks when no longer needed
- Return values in filters - Always return a value from filter callbacks
- Don’t modify arguments - Create new objects/arrays instead