Search code examples
phpwordpressbuddypress

PHP - choose random from SQL query rather than 'foreach'


Just wondering if it was possible to modify this section of code. Right now it heads to the database and automatically joins a WordPress user to a group provided it has been ticked in the admin panel. Rather than 'foreach' group which has been ticked, is it possible to change this so that out of the groups ticked, it will choose a random group to auto-join?

if (!function_exists('update_auto_join_status')) {
    function update_auto_join_status($user_id) {
        global $wpdb, $bp;

        // get list of groups to auto-join.
        $group_list = $wpdb->get_results("SELECT * FROM {$bp->groups->table_name} WHERE auto_join = 1");
        foreach ($group_list as $auto_join_group) {
            groups_accept_invite( $user_id, $auto_join_group->id );
        }
        $wpdb->query("UPDATE {$wpdb->users} SET auto_join_complete = 1 WHERE ID = {$user_id}");
    }

    add_action( 'user_register', 'update_auto_join_status');
}

I'm quite new to PHP - where would I start?

Thanks so much for any help.


Solution

  • You can just ORDER BY RAND() LIMIT 1 to pick a single group at random.

    $group_list = $wpdb->get_results("SELECT id FROM {$bp->groups->table_name} WHERE auto_join = 1 ORDER BY RAND() LIMIT 1");
    groups_accept_invite( $user_id, $group_list[0]->id );