The Problem
We recently had a software development project requirement where we needed to show certain BuddyPress members in the BuddyPress Members Directory. Specifically, BuddyPress members who belonged to certain roles/levels needed to be displayed. For example you may only want to show Administrators or Editors in the members directory or in our case, show only S2Members of a certain membership level.
S2Member is a WordPress membership plugin that works well with BuddyPress. It’s really more than a plugin, it actually more accurately resembles a complete membership framework that works with WordPress similar in scope to BuddyPress. S2Member comes in two flavors, Free & Pro. The free version is amazingly robust and should serve the needs of most basic WordPress / BuddyPress site requirements, however the Pro version offers a full suite of functionality for more complex installations.
The Solution
In our case, we needed to show all WordPress Administrators and S2Members with a membership level of 1 in the directory. The BuddyPress members directory is generated through The Members Loop contained in the directory: plugins/buddypress/bp-themes/bp-default/members/members-loop.php. Members-loop.php is where you’ll modify the code to show only certain types of BuddyPress users instead of the default which shows all users.
The code itself is fairly straightforward. In the while loop that generates each BuddyPress user listing in the directory, you’ll need to get each member’s user id and then get their role. After
add
This sets the variable $user to the current BuddyPress user being fetched in the While loop.
Next, add
$s2member_var = get_user_field ("s2member_access_role", $user);
You can use any variable name here, in our case because we primarily want to show S2Members of level 1, we named our var, $s2member_var. This line gets the user field "s2member_access_role" for the current user in the loop who's user id = $user.
Lastly, we want to only show BuddyPress users in the directory who are Administrators or S2members of level 1. Using a simple 'if' statement, we say if $s2member_var which contains the current user's role (Administrator, Editor, Subscriber, s2member_level0, s2member_level1, s2member_level2, etc.) is exactly equal to "s2member_level1" or "administrator" then show the member in the BuddyPress members directory. If not, skip this user and loop to the next one.
Here's the code to begin the loop:
Here's the entire members-loop.php file for reference. Please note other customizations were done to the loop, including:
1) Listing users in alphabetical order in the BuddyPress members directory
2) Showing BuddyPress custom profile fields in the BuddyPress members directory from the BuddyPress registration form.
3) Removing the "last active" label from each user's BuddyPress members directory listing.
[googleplusauthor]