Skip to:
Content
Pages
Categories
Search
Top
Bottom

Reply To: Sorting by last name goes wrong when having multiple words as last name

@nielspilon

Participant

Nope, it returns an error that there are no members to display. I guess that I could replace ‘Robin van Persie’ with something blank like this

substr( strstr( ' ', ' ' ), 1 )

Just to clarify, this is the full code in my functions.php to sort the members:

 function alphabetize_by_last_name( $bp_user_query ) {
    if ( 'alphabetical' == $bp_user_query->query_vars['type'] )
        $bp_user_query->uid_clauses['orderby'] = "ORDER BY substring_index(u.display_name, ' ', -1)";
}
add_action ( 'bp_pre_user_query', 'alphabetize_by_last_name' );
 
// To reflect the alphabetical sorting of the member directory, you
// could also format the names to show the last name first. Here is
// a helper function to format names as follows: Last, First Middle
// Etc.
//
// To use this function every time a user's name is shown or queried,
// simply add it as a filter:
//
// <code>add_filter ('bp_get_member_name', 'format_last_name_first' );</code>
//
// To only reformat the name in the member directory, change your
// members/members-loop.php file in your (child)theme. Look for
// <code>bp_member_name()</code>
// and replace it with
// <code>echo format_last_name_first ( bp_get_member_name() );</code>
 
/**
 * Helper function for formatting a name: Last, First Middle Etc.
 *
 * @param string $name
 * @return string Formatted name
**/

function format_last_name_first( $name ) {
    if ( $first_space = strrpos( $name, " ") )
        $name = substr( $name, $first_space + 1 ) . ", " . substr( $name, 0, $first_space );
    return $name;
}
 
// BONUS: To make alphabetical sorting the default sorting, use the
// function below. 
//
// In order for this to work properly, <code><option value=&quot;alphabetical&quot;></code>
// must be the first option for the members-order-select in
// members/index.php.
 
function sort_members_alphabetically( $qs = '', $object = false ) {
    if( $object != 'members' ) //for members only
        return $qs;
 
    if ( empty( $qs ) || ! strpos( $qs, "type=" ) ) {
        $args = wp_parse_args($qs);
        $args['type'] = 'alphabetical';
        $args['action'] = 'alphabetical';
 
        $qs = build_query( $args );
    }
 
    return $qs;
}
add_action( 'bp_ajax_querystring', 'sort_members_alphabetically', 11, 2 );

I guess that members are sorted by the default WordPress first and last name fields right? Just because we’ve added some custom fields to the member profile pages to split their names in first name, ‘surname prefix (it’s for words like ‘van’ ‘de’) and last name. Not all members have a surname prefix though.

Skip to toolbar