2

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

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;
}
  • Wow thanks @Dave .. so that means there is a difference between $args[ 'Hello5' ] = 'HELL4'; and $arg = array('Hello5' => 'HELL4') – Kolawole Emmanuel Izzy Sep 6 at 19:30
  • 1
    You got it, Kolawole! Yes, big difference. The former assigns the element Hello5 in $args to HELL4, where the latter assigns the entire $args array to array('Hello5' => 'HELL4') (overwriting the previous values in the process). – Dave Romsey Sep 6 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.