Insert new element to array with add_filter

All we need is an easy explanation of the problem, so here it is.

add_filter('example_filter', function(){ return array( 'tax1' ); } );
add_filter('example_filter', function(){ return array( 'tax2' ); } );
add_filter('example_filter', function(){ return array( 'tax3' ); } );

print_r( apply_filters( 'example_filter', array()) );

Result is

Array ( [0] => tax3 ) 

I couldnt figure out how i can insert new element to this array with add_filter. What is proper way?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Filters work by calling each of the hooked callback functions (in priority order). The value to be filtered is passed to the first callback funtion. The returned value of that callback function is then passed to the second callback, and the returned value from that is passed onto third and so on, until all hooked callbacks have been fired. Whatever the last returned value is (i.e. the filtered value having passed through all the callbacks) is then taken to be the value after the filter has been applied.

In the above example, each filter is ignoring what is passed to it, and instead just returning its own new array.

(Side note: avoid anonymous functions as callbacks)

Try:

add_filter('example_filter', 'my_example_filter_1' );
function my_example_filter_1( $array ){
    $array[]='tax1';
    return $array;
}
add_filter('example_filter', 'my_example_filter_2' );
function my_example_filter_2( $array ){
    $array[]='tax2';
    return $array;
}
add_filter('example_filter', 'my_example_filter_3' );
function my_example_filter_3( $array ){
    $array[]='tax3';
    return $array;
}

print_r( apply_filters( 'example_filter', array()) );

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply