I was wondering if it is possible to filter out a part of a variable, if it is no array. Or can I only replace the whole code, or add code to it?
Let's say I have this code:
$output = '<select>';
$output .= '<option value="option 1">Option 1</option>';
$output .= '<option value="Filter out">Don't show this option</option>';
$output .= '<option value="option 2">Option 2</option>';
$output .= '</select>';
$output = apply_filters( 'my_filter', $output );
return $output;
Is there any way to filter out the second option, without rewriting the whole code in the filter?
Thanks
SOLUTION
My solution was to use str_replace
.
I was wondering if it is possible to filter out a part of a variable, if it is no array. Or can I only replace the whole code, or add code to it?
Let's say I have this code:
$output = '<select>';
$output .= '<option value="option 1">Option 1</option>';
$output .= '<option value="Filter out">Don't show this option</option>';
$output .= '<option value="option 2">Option 2</option>';
$output .= '</select>';
$output = apply_filters( 'my_filter', $output );
return $output;
Is there any way to filter out the second option, without rewriting the whole code in the filter?
Thanks
SOLUTION
My solution was to use str_replace
.
1 Answer
Reset to default -1The documentation is well explicable of the topic, let's have a look here https://developer.wordpress/reference/functions/apply_filters/.
In your specific case my_filter
is applied no matter what, even if there is no value it. To apply the filter only if is_array()
you could insert a specific instruction directly into your filter like:
function example_callback( $output ) {
if(is_array($output)){
//do something and replace part of the string with str_replace()
}
return $output;
}
add_filter( 'my_filter', 'example_callback', 10, 1 );
About the str_replace()
php function read more here http://php/manual/en/function.str-replace.php.
regex
to search for a specific match in a string or useDOMdocument
to query HTML code in php – honk31 Commented Nov 22, 2018 at 16:18