Word Count: 294
  • Post category:Codings
  • Post last modified:2021-03-31

Action Hook

do_action( )

Actions are defined using the do_action($h_name, $args) function.

  • $h_name – This is the hook name and must be unique.
  • $args – optional, one or more variables.

The do_action() functions are usually placed (by programmer) at appropriate locations within php files for templates, plugins, etc.

add_action( )

To call a specific function when an action is taking place, use the add_action( ) function.

add_action($name, function_name, $priority, $noOfArguments)

  • $priority
    • optional.
    • determines the order in which functions will be executed. By default Actions will use the default value of 10. Priority with smaller number will run first. E.g., priority 9 will run before priority 10.
  • $noOfArguments
    • specify how many variables are being passed to the callback function for add_action( ). The default is 1.

Filter Hook

A filter is a hook that accepts a variable or a series of variables and returns them back after being modified.

apply_filters( )

Filters are created by the apply_filters( $tag, $value, $var ) function.

  • $tag – required. The name of the filter.
  • $value – required. Variable value(s) to be filtered.
  • $var – optional. Extra value(s) to be passed to the filter function.

add_filter( )

To executive the filter, use the function add_filter( $tag, $function, $priority, $accepted_args ).

  • $tag – required. The name of the filter.
  • $function – required. The function to be executed.
  • $priority – optional. Default = 10.
  • $accepted_args – optional but mandatory if more than 1 arguments are to be passed to $function. Default = 1.

Example

//make our name value array filterable
$add_name = apply_filters('filter_name_array_values', array('Joanna','Peter')
); 

//Change the saved name values by filtering them
function add_new_names($names){
    $names[] = 'Simon';
    return $names;
}
add_filter('filter_name_array_values','add_new_names');