The do_action_ref_array() WordPress PHP function invokes the callback functions that are attached to a certain action hook. The arguments to the functions are given in an array form.
Usage
Let’s consider a scenario where you have an array of arguments that you want to pass to the callback functions of a specific action hook:
$args = array( 'apple', 7, 'banana', 'cherry' ); do_action_ref_array( 'fruit_action', $args );
This code will execute the same as:
do_action( 'fruit_action', 'apple', 7, 'banana', 'cherry' );
Parameters
- $hook_name (string): The name of the action to be executed.
- $args (array): The arguments supplied to the functions hooked to $hook_name.
More information
See WordPress Developer Resources: do_action_ref_array()
Examples
Basic Usage
In this example, we’re calling an action and passing an array of arguments. This is a straightforward application of the do_action_ref_array() function.
$args = array( 'apple', 7, 'banana', 'cherry' ); do_action_ref_array( 'fruit_action', $args );
Modifying Parameters
In this example, we are specifying separate parameters and also modifying them. It shows how you can manipulate parameters within your hooked functions.
do_action_ref_array( 'wpdocs_my_action', array( &$arg1, &$arg2, &$arg3, &$arg4 ) );
Callback:
add_action( 'wpdocs_my_action', 'wpdocs_my_callback', 10, 4 ); function wpdocs_my_callback( &$arg1, &$arg2, &$arg3, &$arg4 ) { // access and modify values with $arg1, $arg2, etc. }
Multiple Actions
This example shows how you can call multiple actions with different sets of arguments.
$args1 = array( 'apple', 7, 'banana', 'cherry' ); $args2 = array( 'red', 'green', 'blue' ); do_action_ref_array( 'fruit_action', $args1 ); do_action_ref_array( 'color_action', $args2 );
Dynamic Action Name
Here, the action name is dynamic and based on a variable. This is useful when you want to execute actions dynamically.
$action_name = 'dynamic_action'; $args = array( 'arg_1', true, 'foo', 'arg_4' ); do_action_ref_array( $action_name, $args );
No Arguments
The do_action_ref_array() function can be used even when there are no arguments to pass to the hooked functions. In this case, an empty array is used.
do_action_ref_array( 'no_arg_action', array() );