Is it possible to hook 3 different functions to the same filter conditionally, like:
<?php
if(a){
add_filter('the_content', 'fnc_1');
}
else if(b){
add_filter('the_content', 'fnc_2');
}
else{
add_filter('the_content', 'fnc_3');
}
?>
Or if this isn’t possible, then can I pass an additional argument to the same function to flag my 3 different conditions? Something like:
<?php
if(a){
add_filter('the_content', 'fnc_1', 'condition_a');
}
else if(b){
add_filter('the_content', 'fnc_1', 'condition_b');
}
else{
add_filter('the_content', 'fnc_1', 'condition_c');
}
?>
All I could find from my reading is that it has to do something with apply_filters
, but couldn’t get around it.
Please can anyone tell me how to achieve this?
Thanks!
Since it does appear to be an interesting question, I’ll go ahead an compile an answer.
Method 1
Totally fine, will work. Here’s the compact piece of code I used to test it:
function fnc_1( $content ) { return 'func1 :: '.$content; }
function fnc_2( $content ) { return 'func2 :: '.$content; }
function fnc_3( $content ) { return 'func3 :: '.$content; }
$a = false;
$b = false;
if ( $a ) add_filter( 'the_content', 'fnc_1' );
elseif ( $b ) add_filter( 'the_content', 'fnc_2' );
else add_filter( 'the_content', 'fnc_3' );
Method 2
add_filter
does not allow you to pass additional arguments to the filter function, but if you really need to share one function you can wrap a custom filter around the filter like so:
add_filter( 'wpse31470_filter_wrapper', 'wpse31470_filter_wrapper_func', null, 2 );
function wpse31470_filter_wrapper_func( $content, $condition ) {
if ( $condition ) return 'TRUE :: '.$content;
else return 'FALSE ::'.$content;
}
add_filter( 'the_content', 'wpse31470_the_content_filter' );
function wpse31470_the_content_filter( $content ) {
$condition = true;
return apply_filters( 'wpse31470_filter_wrapper', $content, $condition );
}
The purpose of the wpse31470_the_content_filter
is to wrap the argument supplied by the_content
filter and pass it on to your own wpse31470_filter_wrapper
along with any additional arguments.