WordPress Action Hooks
WordPress
Placing do_action( $tag, $arg )
within a theme or plugin allows all functions attached to the action hook $tag to be invoked at this specific point.
A callback function is registered to the action hook by means of the add_action()
function, using the $tag defined in do_action()
.
This enables you to create an API for a theme or plugin - callbacks can be registered for a custom action.
To register a callback, use add_action()
. This will typically be in the theme custom functions, where the related $function_to_add will also be defined:
To execute the callback, use do_action()
. This will typically be in the template or layout partial - anywhere where you’d like to give developers (or yourself) the ability to hook in additional content:
Simplest Example
Simple example of an action hook - allows extra content to be added by the theme.
Register hook before address - added in theme template or plugin layout:
We can now add HTML before the address block, by hooking to the ‘before_address’ action hook. This gives layout control to the theme, which is proper.
The following code would typically be located in the theme custom functions.
Arguments for the Action Hook Callback
The callback function that is registered by means of add_action()
can accept arguments. The number of arguments must agree with those defined in the corresponding do_action()
.
This means that variables defined in the same scope as the do_action()
call can be made available to the callback registered in add_action()
.
Within the template (or better within a function invoked from the template):
Within the theme custom functions:
Resources
comments powered by Disqus