merging an array to an existing array using add_filter

I’m working on a plugin and i want to be able to extend some of the functionality using apply_filters(). I have a setup like this which is the default values;

print_r( apply_filters( 'some_example_hook', array(
    'Hello1'    =>  'HELL0',
    'Hello2',   =>  'HELL1',
    'Hello3',   =>  'HELL2',
    'Hello4',   =>  'HELL3',
) ) );

Now i want to be able to add to the array above (so i can extend the default values) but each time i create a new function and add_filter, it overrides everything in the array with this new array. This is what i mean;

add_filter( 'some_example_hook', 'add_yourself_to_some_examplehook' );
function add_yourself_to_some_examplehook($args) {
    $args = array(
        'Hello5'    => 'HELL4'
    ); 
    return $args;
}

the output will become;

Array ( [Hello5] => HELL4 )

instead of;

Array ( 
    [Hello1] => HELL0,
    [Hello2] => HELL1,
    [Hello3] => HELL2,
    [Hello4] => HELL3,
    [Hello5] => HELL4,
)

So that i can easily do something like this with the arrays anywhere and whenever an array is added to the filter (as we did above from anywhere or any plugin, it should just add the array to the filter and make the code below valid;

if ( in_array('HELL4', apply_filters( 'some_example_hook', array(
    'Hello1'    =>  'HELL0',
    'Hello2',   =>  'HELL1',
    'Hello3',   =>  'HELL2',
    'Hello4',   =>  'HELL3',
  ) ) ) ) {
       //Do Something
       // THIS WILL BE VALID because we have added it using add_filter above
 }

I have tried this method here Insert new element to array with add_filter but the output is just this Array ( [Hello5] => HELL4 ) … it is not appending the array to the existing array. Not sure what i am doing wrong.

Thanks in advance for your help

1 Answer
1

You are overwriting $args in add_yourself_to_some_examplehook(). Based on what you’re saying you want to achieve, you should be appending the new item instead:

add_filter( 'some_example_hook', 'add_yourself_to_some_examplehook' );
function add_yourself_to_some_examplehook($args) {
    $args[ 'Hello5' ] = 'HELL4'; // <-- Note the syntax here.

    return $args;
}

Leave a Comment