BuddyBoss (and BuddyPress), are popular social network plugins for WordPress and provide powerful tools for building community sites. However, customizing their member lists to display only certain user roles can be tricky. In this post, we’ll explore how to modify the BuddyBoss members list to show only users with specific roles using custom code. This can be particularly useful for sites that want to create exclusive areas or ensure that only certain member types are visible in community sections.

Where to Place the Code

The code should be added to your WordPress site’s theme functions.php file, which is located in your current theme’s directory. You can access this file by navigating to Appearance > Theme Editor from your WordPress dashboard or editing your theme files directly via FTP.

Understanding the Code

Here’s the code snippet to place in functions.php:

add_action('bp_pre_user_query_construct', 'custom_bp_members_by_role');

function custom_bp_members_by_role($query) {
    if (empty($query->query_vars['user_id'])) {
        $user_query = new WP_User_Query(array(
            'role__in' => ['myuser'], // Specify the user role names here
            'fields' => 'ID'
        ));
        $user_ids = !empty($user_query->get_results()) ? $user_query->get_results() : array(-1);

        // Modify the include parameter to only include users with the specified role(s)
        $query->query_vars['include'] = $user_ids;
    }
}

Understanding how the Code Works

  1. add_action('bp_pre_user_query_construct', 'custom_bp_members_by_role');
    • This line hooks into BuddyPress’s user query process, allowing us to alter the query before it executes. The bp_pre_user_query_construct is a specific hook provided by BuddyPress for this purpose.
  2. new WP_User_Query(array('role__in' => ['myuser'], 'fields' => 'ID'));:
    • This creates a new WordPress user query that searches for users by role. Here, role__in is an array where you can specify one or more user roles. This example filters users who have the ‘myuser’ role. You can replace ‘myuser’ with any other role as necessary.
  3. $query->query_vars['include'] = $user_ids;:
    • This line modifies the BuddyBoss user query to include only the user IDs returned by our WP_User_Query. If no users match, it defaults to array(-1), ensuring that no users are displayed.

Implementing this code will directly influence how member lists are displayed on your BuddyBoss or BuddyPress platform. Only users with the specified roles will be visible in member directories, which is ideal for sites that have different levels of access or wish to create more curated community experiences.

Leave a Reply

Get in Touch

Please fill out the form below and we will get back to you ASAP

  • This field is for validation purposes and should be left unchanged.