Hooks explained

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$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.

1
2
3
4
function extendableFunction() {
  // ... other function code
  do_action('myextension');
}

To register a function as a hook to that, first we code our function:

1
2
3
function extensionOne() {
  // ... function code ...
}

and then register the hook:

1
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.