2

Im working on a function which gets me lawyers based on criteria. The function works fine. Recently I added a meta key called 'is_endorsed'. The value can be either '1' or '0'.

I need to bring endorsed user on top of results. Since we applied endorsement feature. Some members are set to '1', and some are set to '0'. And most of them don't even have 'is_endorsed' meta key in their wp_usermeta table.

The following code is working without endorsement filter. I've tried every possible modifications I knew, now its taking on my nerves. Please have a look and give me some tips.

function find_lawyer( $country = '', $state = '', $city = '' ) {
    $meta_query = array(
        array(
            'key'     => 'user_locations',
            'compare' => '!=',
            'value'   => ''
        ),
        array(
            'key'     => 'is_published',
            'compare' => '=',
            'value'   => '1'
        ),
    );

    if ( $country ) {
        $meta_query[] = array(
            'key'     => 'user_locations',
            'compare' => 'REGEXP',
            'value'   => '([\w|]*)country:' . $country . '([\w|]*)'
        );
    }

    if ( $state ) {
        $meta_query[] = array(
            'key'     => 'user_locations',
            'compare' => 'REGEXP',
            'value'   => '([\w|]*)state:' . $state . '([\w|]*)'
        );
    }

    if ( $city ) {
        $meta_query[] = array(
            'key'     => 'user_locations',
            'compare' => 'REGEXP',
            'value'   => '([\w|]*)city:' . $city . '([\w|]*)'
        );
    }

    $users_query = new WP_User_Query( array(
        'role'       => 'lawyer',
        'meta_query' => $meta_query
    ) );


    return $users_query->get_results();
}

And here is what I've tried. It gives me only users having 'is_endorsed' = '1'.

function find_lawyer( $country = '', $state = '', $city = '' ) {
    $meta_query = array(
        array(
            'key'     => 'user_locations',
            'compare' => '!=',
            'value'   => ''
        ),
        array(
            'key'     => 'is_published',
            'compare' => '=',
            'value'   => '1'
        ),
        array( 
            'relation' => 'OR',
            array( 
                'key' => 'is_endorsed',
                'value' => '1',
                'compare' => 'EXISTS',
            ),
            array( 
                'key' => 'is_endorsed',
                'compare' => 'NOT EXISTS'
            )             
        )

    ); // And so on...

    $users_query = new WP_User_Query( array(
        'role'       => 'lawyer',
        'meta_query' => $meta_query,
        'orderby' => 'meta_value_num',
    ) );


    return $users_query->get_results();
}

Your Answer

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

Browse other questions tagged or ask your own question.