The simplest implementation of hooks is to have a global array holding the registered hooks, a function to make hook registrations and finally a function to call the corresponding function handlers for a given hook, as shown in the next code segment.
$actions = array();
function add_action( $hook, $function ){
global $actions;
if( !isset( $actions[ $hook ] ) ) {
$actions[ $hook ] = array();
}
$actions[ $hook ][] = $function;
}
function do_action( $hook ) {
global $actions;
if( isset( $actions[ $hook ] ) ) {
foreach( $actions[ $hook ] as $function ) {
call_user_func( $function );
}
}
}
In order to make a function extendable at the desired point of the function we call do_action in order to execute any registered hooks.
function extendableFunction() {
// ... other function code
do_action('myextension');
}
To register a function as a hook to that, first we code our function:
function extensionOne() {
// ... function code ...
}
and then register the hook:
add_action('myextension', 'extensionOne');
Naturally, hook registration must be executed prior the extended function. When extendableFunction is executed, do_action is called and this will call the extensionOne function.