I’m trying to add multiple filters from inside a foreach loop. Unfortunately I can’t get the code to reference the value properly. How do I pass the value from the loop to the function?

The following sets all the filters to null.

foreach ( $myarray as $key => $value ) {
     add_filter( "plugin_filter_$key", function( $value ) { return $value; } );
}

This is my test code and this sets the filters to ‘true’.

foreach ( $myarray as $key => $value ) {
     add_filter( "plugin_filter_$key", function( $value ) { return 'true'; } );
}

1 Answer
1

foreach ( $myarray as $key => $value ) {
     add_filter( "plugin_filter_$key", function () use ( $value ) { return $value; } );
}

Check out the use keyword for closures.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *