hooks - How to filter part of a variable if it is no array?

admin2025-06-06  9

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.

Share Improve this question edited Nov 23, 2018 at 11:34 RobbTe asked Nov 22, 2018 at 15:11 RobbTeRobbTe 2622 silver badges16 bronze badges 3
  • yes you can. you can use regex to search for a specific match in a string or use DOMdocument to query HTML code in php – honk31 Commented Nov 22, 2018 at 16:18
  • Is that really the best/only way to go? – RobbTe Commented Nov 23, 2018 at 9:27
  • 1 Yes, welcome. @RobbTe – middlelady Commented Nov 23, 2018 at 11:37
Add a comment  | 

1 Answer 1

Reset to default -1

The 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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749157397a316852.html

最新回复(0)