alphabetically order role drop-down selection in dashboard

The site I’m working on will have a very large number of unique user roles via a members plugin. Because of that, I’d like to have the Role drop-down selection on the Add New User page to display roles alphabetically, rather than descending order of creation.

Is there any way to do this?

Related posts

Leave a Reply

2 comments

  1. Almost the same approach One Trick Pony has chosen, but I am using translated names and uasort() (to preserve the keys):

    add_filter( 'editable_roles', 't5_sort_editable_roles' );
    
    /**
     * Array of roles.
     *
     * @wp-hook editable_roles
     * @param   array $roles
     * @return  array
     */
    function t5_sort_editable_roles( $roles )
    {
        uasort( $roles, 't5_uasort_editable_roles' );
        return $roles;
    }
    /**
     * Compare translated role names.
     *
     * @param  array $a First role
     * @param  array $b Second role
     * @return number
     */
    function t5_uasort_editable_roles( $a, $b )
    {
        return strcasecmp(
            translate_user_role( $a['name'] ),
            translate_user_role( $b['name'] )
        );
    }
    

    As a plugin on GitHub.

  2. Apparently there’s a filter that you can use in the get_editable_roles function (which is called in that page):

    add_filter('editable_roles', function($roles){
    
      // sort alphabetically (ignores case)
      usort($roles, function($a, $b){
        return strcasecmp($a["name"], $b["name"]);
      });   
    
      return $roles;
    });