Extending BuddyPress Group Hierarchy – Creating a Member Groups list

In this post, I’m going to show you how to create a Member Groups page/list/widget, with a little background on how Group Hierarchy extends the BuddyPress Groups loop.

BuddyPress Groups loop overview

If you aren’t familiar with bp_has_groups() from looking at the BuddyPress theme files, you should take a look at this overview from the BP Codex before continuing.

In a nutshell, bp_has_groups() accepts a series of parameters which it uses to populate the global $groups_template variable with a set of groups. This, in turn, allows all the cool template functions to work without parameters cluttering up your theme file.

How Group Hierarchy changes the Loop

BuddyPress Group Hierarchy changes this in two important ways:

bp_has_groups() creates a set of BP_Groups_Hierarchy objects instead of BP_Groups_Group objects

bp_has_groups_hierarchy() extends the loop with a parent_id parameter for getting only child groups of the passed group ID

There are more changes made just for the Group Tree, but that’s enough to get us started. Onward!

Creating a Member Groups list

Before we build our Member Groups page / widget / list, there’s something you should know about working “in the loop,” i.e. in the context of the current group. The only thing telling BuddyPress what group we’re looking at is the $groups_template variable introduced above. Our member group list is going to change that variable, so we need to save its current state and restore it when we’re done.

// If you're in a function, bring $groups_template into scopeglobal$groups_template;// Save the current group context for later$current_group_template=$groups_template;

Using the Codex article I posted at the top as a reference, you’ll see how easy it is to create a Member Groups page / widget / whatever.

…and the rest works as is! Since 1.3.0, pagination is handled automatically.

Don’t forget to restore the original context!

$groups_template=$current_group_template;

A complete example

Here’s a quick example that adds a list of Member Groups on the Members page, above the list of users. Drop this in your functions.php file, or in a custom plugin, but note that it will only display if the parent group has at least one member!