0

I am trying to get users list sort by metakey. I mean i have set meta key user_last_login. some users doesnot have this meta key. some users have it.

I want to get both users in single query but if metakey exists those will come first and remaining should come last.

Here is my query

$meta_query_args = array(
            'relation' => 'OR', // Optional, defaults to "AND"
            array(
            'key'     => 'user_last_login',                 
            'compare' => 'Not Exists'
            ),
            array(
            'key'     => 'user_last_login',                 
            'compare' => 'Exists'
            )
        );
        $meta_query = new WP_Meta_Query( $meta_query_args );


            $args = array(
                'offset' => $paged ? ($paged - 1) * $number : 0,
                'number' => $number,
                'fields' => 'all',
                'orderby'=>'user_last_login',                   
                'exclude' => array(get_current_user_id()), 

                'meta_query'  =>$meta_query
            );

            $users = get_users( $args );

Please help.

0

You can index each of the arrays and then orderby 1 or both of them using ASC,DESC as per your requirement

    $meta_query_args = array(
        'relation' => 'OR', // Optional, defaults to "AND"
        'no_login' =>array(
        'key'     => 'user_last_login',                 
        'compare' => 'Not Exists'
        ),
        'login' => array(
        'key'     => 'user_last_login',                 
        'compare' => 'Exists'
        )
    );
    $meta_query = new WP_Meta_Query( $meta_query_args );


        $args = array(
            'offset' => $paged ? ($paged - 1) * $number : 0,
            'number' => $number,
            'fields' => 'all',
            'orderby'           => array(
            'login'         => 'ASC'
        ),                   
            'exclude' => array(get_current_user_id()), 

            'meta_query'  =>$meta_query
        );

        $users = get_users( $args );
  • it is returning wrong results. I have 20 users. I have 11th,15th users meta value in the database. so 11th,15th users should come first after remaining users(doesnot have meta key and value) should come. but it is displaying order by default 'login' name. I have changed above index name also. not working – muralikalpana Dec 11 '17 at 4:42

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.