Extending BuddyPress Group Hierarchy – Join to Upstream Groups

Introduction

A frequent feature request for BuddyPress Group Hierarchy has been to automatically join members of a subgroup to its parent groups. While pretty straightforward to implement, there are two main reasons this feature won’t make it into the plugin:

  1. This behavior isn’t appropriate for many or even most setups
  2. Everyone who has requested it has wanted it to work on groups by different criteria — some want groups of a certain depth, others a specific set of groups, others all the children of a certain group. Building a UI that would let this work the way anyone wants would overwhelm the project.

Instead, I decided to post this sample implementation, including a few ways to select groups. Take a look!

The Code

The code below can be included in your theme’s functions.php file, or can be part of a new plugin.

Note for the true novice: you must choose one of the if statements in the block below with this code and substitute the placeholders for things you care about. It will not work pasted as is.

/* groups_join_group is called whenever someone joins a group in both BP 1.2 and 1.5.x */
add_action('groups_join_group', 'my_join_group_action', 10, 2);
 
function my_join_group_action( $group_id, $user_id ) {
 
	/* This part is critical - you must select ONLY the groups you want to START this chain
	 * This function will recurse up to the toplevel on its own, so if you have a parent group
	 * in the list, you will waste resources trying to join the same group multiple times
	 * as this function is called on each step up the tree
	 */ 
	/** Pick from a list of groups */
	if( in_array( $group_id, ARRAY_OF_GROUPS_I_CARE_ABOUT ) ) {
	/* -- OR -- */
	/** Select groups by depth */
	if( count( bp_group_hierarchy_get_parents() ) == DEPTH_OF_GROUP_I_CARE_ABOUT_EG_3 ) {
	/* -- OR ANYTHING ELSE YOU LIKE */
 
		/* However you choose to select groups, once the group_id matched this part will 
		 * walk up the tree, joining the user to each parent group along the way
		 */
 
		$parents = bp_group_hierarchy_get_parents();
		foreach( $parents as $parent_group_id ) {
			groups_join_group( $parent_group_id, $user_id );
		}
	}
}

If this helps you, or if you have some code to select the groups that matter to YOU, feel free to post in the comments below!

5 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>