A hook is a programming technique that allows you to inject or execute custom code at specific points in a program’s execution. Hooks are especially useful for building modular, extensible systems, such as plugins or CMS frameworks.
PHP itself does not have built-in hook functions like JavaScript or WordPress. However, you can create your own hook system or use one in platforms like WordPress or Laravel (events/listeners).
Types of Hooks
Hook Type | Purpose | Returns Value? |
---|---|---|
Action | Executes custom code (e.g., log, redirect) | ❌ No |
Filter | Modifies and returns data | ✅ Yes |
List of Common Hook Names
Hook Name | Type | Description |
---|---|---|
init |
Action | Runs after system initializes |
wp_footer |
Action | Injects content before </body> |
the_title |
Filter | Modifies post title |
the_content |
Filter | Modifies post content |
save_post |
Action | Runs when a post is saved |
login_redirect |
Filter | Changes redirect URL after login |
admin_menu |
Action | Adds items to admin menu |
Example 1: Create a Custom Action Hook System
HookManager.php
class HookManager {
private $actions = [];
public function add_action($hook_name, $callback) {
$this->actions[$hook_name][] = $callback;
}
public function do_action($hook_name, ...$args) {
if (!empty($this->actions[$hook_name])) {
foreach ($this->actions[$hook_name] as $callback) {
call_user_func_array($callback, $args);
}
}
}
}
// Usage
$hooks = new HookManager();
// Register an action
$hooks->add_action('on_load', function($name) {
echo "Hello, $name! Page loaded.
";
});
// Trigger the action
$hooks->do_action('on_load', 'John');
Output:
Hello, John! Page loaded.
Example 2: Create a Custom Filter Hook System
FilterManager.php
class FilterManager {
private $filters = [];
public function add_filter($hook_name, $callback) {
$this->filters[$hook_name][] = $callback;
}
public function apply_filters($hook_name, $value) {
if (!empty($this->filters[$hook_name])) {
foreach ($this->filters[$hook_name] as $callback) {
$value = call_user_func($callback, $value);
}
}
return $value;
}
}
// Usage
$filters = new FilterManager();
// Register a filter
$filters->add_filter('format_title', function($title) {
return strtoupper($title);
});
$filters->add_filter('format_title', function($title) {
return ">> $title <<"; }); // Apply the filter echo $filters->apply_filters('format_title', 'Hello World');
Output:
>> HELLO WORLD <<
Summary
Concept | Function Used |
---|---|
Register Action | add_action() |
Trigger Action | do_action() |
Register Filter | add_filter() |
Apply Filter | apply_filters() |