Skip to:
Content
Pages
Categories
Search
Top
Bottom

Filter Users by Groups


  • Garrett Hyder
    Participant

    @garrett-eclipse

    Hello,

    Wanted to provide some code for those that’ll find it useful as well as suggest this as a Feature.

    I’ve written two functions that work together to provide a filter on the Users panel in WordPress so you can then query by Group Members and have it load the user list.

    // Update User Query Filter for Group Member Filter
    add_filter( 'pre_user_query', array( $this, 'bp_group_members_filter_query' ) );
    add_action( 'restrict_manage_users', array( $this, 'bp_group_members_filter' ), 20 );
    
    // Group Members Query Filter
    function bp_group_members_filter_query( $query ) {
        global $bp, $wpdb, $wp_query, $pagenow;
    
        if ( ! is_admin() || $pagenow != 'users.php' )
            return $query;
    
        if ( isset( $_GET['group'] ) && ! empty( $_GET['group'] ) ) {
            $group_id = $_GET['group'];
            $query->query_from .= " INNER JOIN {$bp->groups->table_name_members} ON {$wpdb->users}.<code>ID</code> = {$bp->groups->table_name_members}.<code>user_id</code>";
            $query->query_where .= " AND {$bp->groups->table_name_members}.<code>group_id</code> = '{$group_id}'";
        }
    
        return $query;
    
    }
    
    // Group Members Filter
    function bp_group_members_filter() {
        global $wpdb;
        $groups = $wpdb->get_results("SELECT * FROM wp_bp_groups");
    
        if ( ! empty( $groups ) ) { ?>
            <label class="screen-reader-text" for="group"><?php esc_html_e( 'Filter by Group', 'wplms-customizer' ); ?></label>
            <select name="group" id="group" class="group-filter" style="display:inline-block; float:none;">
                <option value=''><?php esc_html_e( 'Filter by Group', 'wplms-customizer' ); ?></option>
            <?php foreach ( $groups as $group ) : ?>
                <option value="<?php echo esc_attr( $group->id ); ?>"<?php if ( isset( $_GET['group'] ) && ! empty( $_GET['group'] ) && $_GET['group'] == $group->id) { echo ' selected="selected"'; } ?>><?php echo $group->name; ?></option>
            <?php endforeach; ?>
            </select>
            <?php
            submit_button( __( 'Filter', 'wplms-customizer' ), 'secondary', 'bp-filter-users', false );
    
            wp_nonce_field( 'bp-filter-users', 'bp-filter-users-nonce' );
        }
    }

    Feel free to provide feedback and use for your own site. Would love to see this become a feature in a future release.

    All the best,
    Cheers

  • The topic ‘Filter Users by Groups’ is closed to new replies.
Skip to toolbar