Using WordPress ‘apply_filters_ref_array()’ PHP function

The apply_filters_ref_array() WordPress PHP function calls the callback functions that have been added to a filter hook. This function is identical to apply_filters(), but the arguments passed to the functions hooked to $hook_name are supplied using an array.

Usage

Here’s a simple example of how to use apply_filters_ref_array():

$args = array( 'arg_1', true, 'foo', 'arg_4' );
apply_filters_ref_array( 'my_custom_filter', $args );

Parameters

  • $hook_name (string) – The name of the filter hook.
  • $args (array) – The arguments supplied to the functions hooked to $hook_name.

More information

See WordPress Developer Resources: apply_filters_ref_array()
Please note that as of PHP 5.4, the array is no longer passed by reference.

Examples

Basic usage

This example shows the most basic usage of the function, passing an array of arguments to a custom filter.

// Define the arguments.
$args = array( 'apple', true, 'orange', 'banana' );

// Apply the filter.
apply_filters_ref_array( 'my_fruit_filter', $args );

Accessing array values in callback

This example shows how to access array values within a callback function.

function my_fruit_callback( $args ) {
  // Access values with $args[0], $args[1] etc.
  echo "First fruit: " . $args[0]; // Outputs: First fruit: apple
}

add_filter( 'my_fruit_filter', 'my_fruit_callback' );

Modifying array values in callback

This example demonstrates modifying array values within a callback function.

function my_fruit_callback( $args ) {
  // Modify array values.
  $args[0] = 'grape';
}

add_filter( 'my_fruit_filter', 'my_fruit_callback' );

// The first argument will now be 'grape' instead of 'apple'.

Passing a reference pointer

This example shows how to pass a reference pointer as an array element.

apply_filters_ref_array( 'my_fruit_filter', array( &$args ) );

function my_fruit_callback( &$args ) {
  // Access values with $args[0], $args[1] etc.
  echo "First fruit: " . $args[0]; // Outputs: First fruit: apple
}

add_action('my_fruit_filter', 'my_fruit_callback');

Copying array elements into parameters

This example shows how to copy array elements into parameter variables.

function my_fruit_callback( $arg1, $arg2, $arg3, $arg4 ) {
  // Access values with $arg1, $arg2 etc.
  echo "First fruit: " . $arg1; // Outputs: First fruit: apple
}

add_action( 'my_fruit_filter', 'my_fruit_callback', 10, 4 );

In all examples, replace ‘my_fruit_filter’ and ‘my_fruit_callback’ with your own filter and callback function names.