Created
February 26, 2017 12:32
-
-
Save gabrielmerovingi/7ee6d695b65d7c7ceb95f2c9fcc97840 to your computer and use it in GitHub Desktop.
Example showing how we can query a users position in the leaderboard.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Query Custom BP Leaderboard Position | |
* @since 1.0 | |
* @version 1.0 | |
*/ | |
function mycred_pro_query_custom_position( $position, $group_id, $user_id, $point_type ) { | |
// Get setup | |
$setup = mycred_get_bp_group_setup( $group_id ); | |
// This function should only handle our custom type | |
if ( $setup['type'] != 'annual' ) return $position; | |
global $wpdb, $mycred; | |
$until = current_time( 'timestamp' ); | |
$from = mktime( 0, 0, 0, 1, 1, date( 'Y', $until ) ); | |
$group_table = $wpdb->prefix . 'bp_groups_members'; | |
$position = false; | |
$members = groups_get_total_member_count( $group_id ); | |
$position = $wpdb->get_var( $wpdb->prepare( " | |
SELECT rank FROM ( | |
SELECT s.*, @rank := @rank + 1 rank FROM ( | |
SELECT l.user_id, SUM( t.creds ) AS Balance | |
FROM {$mycred->log_table} l | |
LEFT JOIN {$group_table} g ON ( g.user_id = l.user_id ) | |
WHERE g.group_id = %d | |
AND g.is_confirmed = 1 | |
AND g.is_banned = 0 | |
AND l.ctype = %s | |
AND l.time BETWEEN %d AND %d | |
GROUP BY l.user_id | |
) s, (SELECT @rank := 0) init | |
ORDER BY Balance DESC, s.user_id ASC | |
) r | |
WHERE user_id = %d", $group_id, $point_type, $from, $until, $user_id ) ); | |
// If we could not find a position, the user has not yet earned any points for this timeframe | |
// so we return them as being last. | |
if ( $position === NULL ) | |
$position = $members; | |
// A position was found, save it now | |
else { | |
$saved = mycred_get_users_bp_group_positions( $user_id, $group_id ); | |
$saved[ $point_type ] = $position; | |
update_user_meta( $user_id, '_bp_leaderboard_position' . $group_id, $saved ); | |
} | |
return $position; | |
} | |
add_filter( 'mycred_bp_leaderboard_find_position', 'mycred_pro_query_custom_position', 10, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment