Get more accurate results searching with 2 fields

Question

I have a text field and a select menu.

If I choose only from the select menu it shows me all those results as expected. However, if I enter a name in the text field and choose a location from the dropdown it should only show me users with that name in that location. Currently is shows me that user, but also shows all other users in that location.

$s_query = $_GET['s'];
$country = $_GET['location'];

$names = preg_split( '/ +/', trim( $s_query ), 2 );

$meta_query = [];

if ( $s_query ) {
    $name_query = [];

    if ( ! empty( $names[0] ) ) {
        $name_query[] = [ 
            'key'     => array('first_name', 'last_name' ),
            'value'   => $names[0],
            'compare' => 'LIKE',
        ];
    }

    if ( ! empty( $names[1] ) ) {
        $name_query[] = [ 
            'key'     => 'last_name',
            'value'   => $names[1],
            'compare' => 'LIKE',
        ];
    }


    if ( ! empty( $name_query ) ) {
        $name_query['relation'] = 'AND';
        $meta_query[] = $name_query;
    }
}

if ( $country ) {
    $meta_query[] = [
        'key'     => 'location',
        'value'   => $country,
        'compare' => 'LIKE',
    ];
}


$meta_query['relation'] = ( $s_query && $country ) ? 'AND' : 'OR';

$current_page = get_query_var('paged') ? (int) get_query_var('paged') : 1;
$users_per_page = 10;

$args = [
    'meta_query' => $meta_query,
    'number'     => $users_per_page,
    'paged' => $current_page,

];
0
user8463989 4 months 2020-12-22T02:10:38-05:00 0 Answers 5 views 0

Leave an answer

Browse
Browse