What is the best way to reset a search on a meta_key / meta_value?

I’ve build several search forms with different and .

I use a meta_query and build an array of key/value pair.

Array
(
    [relation] => AND
    [0] => Array
        (
            [relation] => AND
            [0] => Array
                (
                    [fields] => ID
                    [key] => ville
                    [value] => Angers
                    [compare] => LIKE
                    [type] => CHAR
                )

        )

    [1] => Array
        (
            [relation] => OR
        )

    [2] => Array
        (
            [relation] => OR
        )

)

It works, i can filter users ou post (i use WP_User_Query or WP_Query).

The serach form is using AJAX, it means that each time a user change a select, the $query_array is updated and the list of s is also updated.

So, le’s say the default value of a select is 0

<option selected="" value="0"> -- Compétences -- </option>

In this case, i reset the meta_key / meta_value :

if (!empty($_POST['ville']) && $_POST['ville'] != '0') {

        $meta_value_ville = $_POST['ville'];
        array_push($query_array_and, array('fields' => 'ID', 'key' => 'ville', 'value' => $meta_value_ville, 'compare' => 'LIKE', 'type' => 'CHAR'));
    } else if ($_POST['ville'] === '0') {
        // reset
        array_push($query_array_and, array('fields' => 'ID', 'key' => 'ville', 'value' => '', 'compare' => 'LIKE', 'type' => 'CHAR'));
    }

I empty the key and the value.
The result is

Array
(
    [relation] => AND
    [0] => Array
        (
            [relation] => AND
            [0] => Array
                (
                    [fields] => ID
                    [key] => 
                    [value] => 
                    [compare] => LIKE
                    [type] => CHAR
                )

        )

    [1] => Array
        (
            [relation] => OR
        )

    [2] => Array
        (
            [relation] => OR
        )

)

Is it the best way to do it ? I feel that sometime the lits of posts or users is not complete with this method.

Read more here: What is the best way to reset a search on a meta_key / meta_value?

Leave a Reply

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