Skip to content

Instantly share code, notes, and snippets.

@shanebp
Last active September 30, 2017 14:04
Show Gist options
  • Save shanebp/6e48a2a550b43db1e67b to your computer and use it in GitHub Desktop.
Save shanebp/6e48a2a550b43db1e67b to your computer and use it in GitHub Desktop.
Members Loop - add Sort By option
// add a Sort By option to the members loop.
// this code assumes that the 'Extended Profile' (xprofile) component is activated
// this code assumes that a Profile Field called 'Price' and of type = 'Number' has been created
function shanebp_add_sortby_price() {
?>
<option value="price">Price</option>
<?php
}
add_action( 'bp_members_directory_order_options', 'shanebp_add_sortby_price' );
function shanebp_filter_ajax_querystring( $querystring = '', $object = '' ) {
if( $object != 'members' )
return $querystring;
$defaults = array(
'type' => 'active',
'action' => 'active',
'scope' => 'all',
'page' => 1,
'per_page' => 0,
'user_id' => 0,
'search_terms' => '',
'exclude' => false,
);
$ch_querystring = wp_parse_args( $querystring, $defaults );
if( $ch_querystring['type'] == 'price' ) {
$ch_querystring['per_page'] = 2;
return $ch_querystring;
}
else
return $querystring;
}
add_filter( 'bp_ajax_querystring', 'shanebp_filter_ajax_querystring', 20, 2 );
function shanebp_users_sortby_price( $object ) {
global $wpdb, $bp;
// Only run this if price option is selected
if ( ! in_array( $object->query_vars['type'], array( 'price' ) ) )
return;
$field_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$bp->profile->table_name_fields} WHERE name = %s", $object->query_vars['type'] ) );
$object->uid_name = 'user_id';
$object->uid_table = $bp->profile->table_name_data;
$object->uid_clauses['select'] = "SELECT u.{$object->uid_name} as id FROM {$object->uid_table} u";
$object->uid_clauses['where'] = " WHERE " . $wpdb->prepare( "u.field_id = %d", $field_id );
$object->uid_clauses['orderby'] = "ORDER BY CAST(u.value AS SIGNED)";
$object->uid_clauses['order'] = "DESC";
$page = $object->query_vars['page'];
$per_page = 2;
$object->uid_clauses['limit'] = $wpdb->prepare( "LIMIT %d, %d", intval( ( $page - 1 ) * $per_page ), intval( $per_page ) );
//return $object; //don't need this as the object is passed by reference
}
add_action( 'bp_pre_user_query', 'shanebp_users_sortby_price' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment