Ammar Ul Hassan February 2016

Sorting custom Column in users section not working fine in wordpress

I am using this code to sort my users list in admin/users. Its not working well as it is still sorting on the basis of user name and email(default worpress sorting columns) How can i only sort my users list on the basis of my custom user meta key and its value "store_name" and not default word press columns.

Code till now

// Register the column as sortable    
function Store_name_column_register_sortable($columns) {
    $columns['Store_name'] = 'Store_name';
    return $columns;
}

add_filter('manage_users_sortable_columns', 'Store_name_column_register_sortable');

function Store_name_column_orderby($vars) {
    if (isset($vars['orderby']) && 'Store_name' == $vars['orderby']) {
        $vars = array_merge($vars, array(
            'meta_key' => 'Store_name',
            'orderby' => 'meta_value'
        ));
    }
    return $vars;
}
add_filter('request', 'Store_name_column_orderby');

Answers


WisdmLabs February 2016

Add order=>'asc' or 'desc'

function Store_name_column_register_sortable( $columns ) {
    $columns['Store_name'] = 'Store_name';
    return $columns;
}
add_filter( 'manage_users_sortable_columns', 'Store_name_column_register_sortable' );

function Store_name_column_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'company' == $vars['orderby'] ) {
        $vars = array_merge( $vars, array(
            'meta_key' => 'company',
            'orderby' => 'meta_value',
            'order'     => 'asc'
        ) );
    }
    return $vars;
}
add_filter( 'request', 'Store_name_column_orderby' );


Ammar Ul Hassan February 2016

So finally i have found the answer after long search. We have to tell WordPress how we want to sort. In WordPress 4.2 sorting by numeric value became much more easier in WP_User_Query. Here is helpful URL New Code:

/**
* Add sortable columns.
*
* @since  1.0.0
* @return void
*/
function prefix_sortable_columns( $columns ) {
$columns['Store_name'] = 'Store_name';
$columns['DATE'] = 'DATE';
return $columns;

}
add_filter( 'manage_users_sortable_columns', 'prefix_sortable_columns' );

/**
* Sort by expire date. Meta key is called 'DATE'.
*
* @since  1.0.0
* @return void
*/
function prefix_sort_by_expiration_date( $query ) {
if ( 'Store_name' == $query->get( 'orderby' ) ) {
    $query->set( 'orderby', 'meta_value' );
    $query->set( 'meta_key', 'Store_name' );
}
if ( 'DATE' == $query->get( 'orderby' ) ) {
    $query->set( 'orderby', 'meta_value_num' );
    $query->set( 'meta_key', 'DATE' );
}
}
add_action( 'pre_get_users', 'prefix_sort_by_expiration_date' );

Post Status

Asked in February 2016
Viewed 3,975 times
Voted 10
Answered 2 times

Search




Leave an answer