Reputation: 5037
I have implemented some custom sort options on the member directory of buddypress. The one I am having an issue with is sort by Last Name (a xprofile field). When I print_r
the results of the query to the screen the user ID's are in the order I want them displayed in but when I visit the page the members are not in that order. Reading up on bp_ajax_querystring I see you can pass ORDER and ORDERBY but anything I have tried doesnt work. The members should display in alphabetical order by last name.
Here is the piece of code with the query.
if( $ch_querystring['type'] == 'alphabetical-last' ){
global $wpdb;
$field_id = 518; //Last name field ID
$query = "SELECT user_id FROM " . $wpdb->prefix . "bp_xprofile_data WHERE field_id = " . $field_id . " ORDER BY " . $wpdb->prefix . "bp_xprofile_data.value ASC";
$custom_ids = $wpdb->get_col( $query );
// convert the array to a csv string
$user_str = implode(",", $custom_ids);
echo '<pre>';
print_r($user_str); //Prints the ID's I would like the members to be displayed in
echo '</pre>';
$ch_querystring['include'] = $user_str;
//$ch_querystring['type'] = 'alphabetical';
$ch_querystring['per_page'] = 500;
$ch_querystring['exclude'] = '1,1101,1030';
//$ch_querystring['orderby'] = "ORDER BY FIELD(value," . $ch_querystring['include'] . ")"; //Doesnt Work
//$ch_querystring['order'] = 'DESC'; //ASC and DESC doesnt work
echo '<pre>';
print_r($ch_querystring);
echo '</pre>';
return $ch_querystring;
}
For debugging here is what $ch_querystring
returns:
Array
(
[type] => alphabetical-last
[action] => alphabetical-last
[scope] => all
[page] => 1
[user_id] => 0
[search_terms] =>
[exclude] => 1,1101,1030
[per_page] => 500
[include] => 1511,1499,1477,1483,1,1512,1510,1482,1503,1514,1498,1502,1506,1484,1479,1492,1497,1488,1495,1508,1475,1481,1501,1515,1478,1491,1490,1505,1487,1509,1480,1507,1485,1493,1513,1500,1516,1496,1476,1489,1504,1494,1486,1474
[orderby] => ORDER BY FIELD(value,1511,1499,1477,1483,1,1512,1510,1482,1503,1514,1498,1502,1506,1484,1479,1492,1497,1488,1495,1508,1475,1481,1501,1515,1478,1491,1490,1505,1487,1509,1480,1507,1485,1493,1513,1500,1516,1496,1476,1489,1504,1494,1486,1474)
)
Here is a link to a paste with the full code in case it helps
Upvotes: 0
Views: 1582
Reputation: 5037
I needed a helper function to sort the query using something similar to this: https://buddypress.org/support/topic/sort-user-list-by-last-name/
//Helper for sorting by last name
function alphabetize_by_last_name( $bp_user_query ) {
if ( 'alphabetical-last' == $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' );
Upvotes: 0