Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.
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?

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

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()) );
share|improve this answer
    
is there any good reason to not use anonymous functions for filters if you dont need to use remove_filter and if u dont need to call that function again? –  Ünsal Korkmaz Jun 18 '12 at 15:05
1  
Well, its good practise not to use them because 1. Improved readability. 2. Extendible code. 3. They aren't supported in PHP 5.2. And there are no benefits to using anonymous functions. –  Stephen Harris Jun 18 '12 at 15:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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