If you want to make the array filterable, use apply_filters()
and add_filter()
. Also, you have to pass the array as an argument to apply_filters()
and expect it in your callback that is changing that array.
Here is a basic example with slightly more meaningful names:
First we have a function that is running over an array of color names and values in order to print these with a styled example. It offers a hook, so other code (theme, plugins) can change the colors: apply_filters( 'arr_colors', $colors );
.
function print_colors()
{
$colors = [
'red' => '#f00',
'green' => '#0f0',
'blue' => '#00f',
];
$colors = apply_filters( 'arr_colors', $colors );
foreach ( $colors as $name => $color ) {
printf(
'%1$s: <span style="background: %2$s;> </span><br>',
$name,
$color
);
}
}
Now we create a callback function elsewhere that can change the color. Note the check for isset ( $colors['green'] )
: There may be more than one callback listening on that hook, so green
could have been removed already before our callback is running. Always keep that in mind.
/**
* @param array $colors
* @return array
*/
function change_colors( array $colors )
{
// remove red
unset( $colors['red'] );
// soften the green
if ( isset ( $colors['green'] ) ) {
$colors['green'] = '#5f5';
}
// add fuchsia
$colors['fuchsia'] = '#f0f';
return $colors;
}
And now we register said callback for the hook in the first function:
add_filter( 'arr_colors', 'change_colors' );
That’s all.