bp_admin_repair_friend_count()

Recalculate friend counts for each user.

Description

Return

(array)

Source

File: bp-core/admin/bp-core-admin-tools.php

442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
function bp_admin_repair_friend_count() {
    global $wpdb;
 
    if ( ! bp_is_active( 'friends' ) ) {
        return;
    }
 
    $statement = __( 'Counting the number of connections for each user… %s', 'buddyboss' );
    $result    = __( 'Failed!', 'buddyboss' );
 
    $sql_delete = "DELETE FROM {$wpdb->usermeta} WHERE meta_key IN ( 'total_friend_count' );";
    if ( is_wp_error( $wpdb->query( $sql_delete ) ) ) {
        return array( 1, sprintf( $statement, $result ) );
    }
 
    $bp = buddypress();
 
    // Walk through all users on the site.
    $total_users = $wpdb->get_row( "SELECT count(ID) as c FROM {$wpdb->users}" )->c;
 
    $updated = array();
    if ( $total_users > 0 ) {
        $per_query = 500;
        $offset    = 0;
        while ( $offset < $total_users ) {
            // Only bother updating counts for users who actually have friendships.
            $friendships = $wpdb->get_results( $wpdb->prepare( "SELECT initiator_user_id, friend_user_id FROM {$bp->friends->table_name} WHERE is_confirmed = 1 AND ( ( initiator_user_id > %d AND initiator_user_id <= %d ) OR ( friend_user_id > %d AND friend_user_id <= %d ) )", $offset, $offset + $per_query, $offset, $offset + $per_query ) );
 
            // The previous query will turn up duplicates, so we
            // filter them here.
            foreach ( $friendships as $friendship ) {
                if ( ! isset( $updated[ $friendship->initiator_user_id ] ) ) {
                    BP_Friends_Friendship::total_friend_count( $friendship->initiator_user_id );
                    $updated[ $friendship->initiator_user_id ] = 1;
                }
 
                if ( ! isset( $updated[ $friendship->friend_user_id ] ) ) {
                    BP_Friends_Friendship::total_friend_count( $friendship->friend_user_id );
                    $updated[ $friendship->friend_user_id ] = 1;
                }
            }
 
            $offset += $per_query;
        }
    } else {
        return array( 2, sprintf( $statement, $result ) );
    }
 
    return array( 0, sprintf( $statement, __( 'Complete!', 'buddyboss' ) ) );
}

Changelog

Changelog
Version Description
BuddyPress 2.0.0 Introduced.

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.