Skip Navigation

[Resolved] Sorting a user view by user’s last name

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Kolkata (GMT+05:30)

This topic contains 1 reply, has 1 voice.

Last updated by lesleeM 2 weeks, 5 days ago.

Assisted by: Minesh.

Author
Posts
#2786052

I am trying to accomplish the same thing the person in this older ticket was trying to do.

https://toolset.com/forums/topic/sort-users-view/

I want to set up a View that outputs users and I want to have them sorted alphabetically by the last name of the user. The solution provided in this older ticket leads to a dead page. Can you assist with providing whatever code snippet is needed to accomplish this? Last Name is not one of the options provided for sorting in the User View.

#2786082

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Hello. Thank you for contacting the Toolset support.

Well - as shared with the ticket.

Toolset uses the WP_User_Query function to query Users, and there is no option to query by last name. This is a limitation of WordPress:
- https://codex.wordpress.org/Class_Reference/WP_User_Query#Order_.26_Orderby_Parameters

As you may notice there is no option available to sort the user query by last_name.

As a workaround:
- edit your view and navigate to "Query Filter" section:
- Add a query filter for the last name field where last_name is a string different from emppy value

Screenshot:
- https://toolset.com/wp-content/uploads/2017/10/577542-lastname.JPG

Then navigate to: Toolset => Settings => Custom Code tab and add a code snippet and add the following code to the code snippet you create and activate the code snippet.

To order by user's last_name, please try to use the hook "wpv_filter_user_query":

add_filter('wpv_filter_user_query', 'func_sort_user_view_by_last_name', 999, 3);
function func_sort_user_view_by_last_name($query_args, $view_settings, $view_id){
    if($view_id == 99999 )  {    
       $query_args['orderby'] = 'meta_value';
       $query_args['order'] = 'ASC';
       $query_args['meta_key'] = 'last_name';
    }
    
return $query_args;
}

Where:
- Replace 99999 with your original user view ID.

More info:
- https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_user_query
- https://toolset.com/documentation/programmer-reference/adding-custom-code/using-toolset-to-add-custom-code/#adding-custom-php-code-using-toolset

Can you please try to use the above code and check that if that help you to resolve your issue.

#2786725

Perfect!!! Thanks a bunch, as always.