Display sortable User meta column in admin panel user’s page

Question

I have defined login levels for users registered on my site as Level 1 and Level 2. I have added a column for same in admin panel users page (users.php), I’m trying to add sorting option but on click for sorting not working. The meta key is level. Here’s what I tried.

add_filter( 'manage_users_columns', 'myplugin_manage_users_columns');
function myplugin_manage_users_columns( $columns )
{
    $columns['login_level'] = 'Login Level';
    return $columns;
}

add_filter('manage_users_custom_column',  'myplugin_manage_users_custom_column', 10, 3);
function myplugin_manage_users_custom_column( $value, $column_name, $user_id )
{
    $user = get_userdata( $user_id );

    if ('login_level' == $column_name){
        $lLevel =  get_user_meta( $user_id, 'level', true );
        $value = $lLevel;
        return $value;
    }
}


//make the new column sortable
function user_sortable_columns( $columns ) {
$columns['login_level'] = 'login_level';
return $columns;
}
add_filter( 'manage_users_sortable_columns', 'user_sortable_columns' );

//set instructions on how to sort the new column

function my_user_query($userquery){
if('login_level'==$userquery->query_vars['orderby']) {
global $wpdb;
$userquery->query_from .= " LEFT OUTER JOIN $wpdb->usermeta AS alias ON ($wpdb->users.ID = alias.user_id) ";//note use of alias
$userquery->query_where .= " AND alias.meta_key = 'level' ";//which meta are we sorting with?
$userquery->query_orderby = " ORDER BY alias.meta_value ".($userquery->query_vars["title"] == "ASC" ? "asc " : "desc ");//set sort order
}
}
0
Akshat 2 months 0 Answers 10 views 0

Leave an answer