How to make a wordpress search more friendly, this code does an excellent job if there is a $ _GET variable, but if it is missing, it simply returns array (0). How to make it so that the search is carried out only when there is a $ _GET variable?

$test = get_posts([ 'meta_query' => [ [ 'key' => 'Город', 'value' => $_GET['city'] ], [ 'key' => 'Область', 'value' => $_GET['address'] ], [ 'key' => 'Режим дня', 'value' => $_GET['rejim'] ] ]]); 

    1 answer 1

    Wrap it in if:

     $meta_query = array(); if (isset($_GET['city'])) { $meta_query[] = [ 'key' => 'Город', 'value' => $_GET['city'] ]; } if (isset($_GET['address'])) { $meta_query[] = [ 'key' => 'Область', 'value' => $_GET['address'] ]; } if (isset($_GET['rejim'])) { $meta_query[] = [ 'key' => 'Режим дня', 'value' => $_GET['rejim'] ]; } $test = get_posts([ 'meta_query' => $meta_query ]); 
    • And what if they are many? Updated example. - asd
    • updated the answer ... - KAGG Design
    • Does not filter, returns all records - asd
    • Does it work all the same? - KAGG Design
    • Yes, it works, thank you very much! - asd