-1

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.

  • 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 Nov 22 '18 at 16:18
  • Is that really the best/only way to go? – RobbTe Nov 23 '18 at 9:27
  • 1
    Yes, welcome. @RobbTe – huraji Nov 23 '18 at 11:37
-1

The documentation is well explicable of the topic, let's have a look here https://developer.wordpress.org/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.net/manual/en/function.str-replace.php.

  • Sorry, this is not what i meant. It is not an array, so checking for it does not make sense. I just have a variable and want to take some content from it and replace it with some other content. Then return the variable. Thanks – RobbTe Nov 23 '18 at 9:28
  • @RobbTe it doesn't make sense that you thumb down my answer when you specifically describe in your question "if it is possible to filter out a part of a variable, if it is no array". My answer is a general overview to WP filters and how you can check for arrays (or not) like ASKED. Further, concerning the rest is a PHP question, not a WP related one. – huraji Nov 23 '18 at 11:28
  • Again, that was not my question. I did not downvote. Thanks – RobbTe Nov 23 '18 at 11:31
  • Do you realise that you wrote that or it could be misleading right? – huraji Nov 23 '18 at 11:35
  • Yes I do, but due to my sample code i thought i would be clear. – RobbTe Nov 23 '18 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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