Automatically subscribe to Buddypress group forum

On a Buddypress and BBPress enabled Word­Press site, I wanted to set things up so that when a mem­ber joins a group, he/she will also auto­mat­ic­ally be sub­scribed to its for­um. I couldn’t find a clear descrip­tions of how to do this, so I thought I’d share what worked for me.

First, here’s the code. You can pas­te this into the functions.php file in your theme dir­ect­ory, or the bp-custom.php file in your plu­gins dir­ect­ory. I think it should work as is so long as you only have one for­um per group.

// Add member who joins a group to its forum
add_action( 'groups_join_group', 'auto_subscribe_forum', 10, 2 );
// function triggered when user joins group
function auto_subscribe_forum ( $group_id, $user_id ) {
// checks to see if there's a user ID
if( !$user_id ) return false; 
// Get's an array of forum IDs for the group
$forum_ids = bbp_get_group_forum_ids( $group_id ); 
// checks to see if there is a forum ID
if ( !empty( $forum_ids ) ) {
// gets the first value from the array, assuming there is one forum
$forum_id = array_shift( $forum_ids );
// subscribes user to forum
bbp_add_user_forum_subscription( $user_id, $forum_id ); 

Basic­ally, you’re using the groups_join_group handle to trig­ger an action when someone joins a group (for example, by select­ing the join group button/link on the group’s home page). The only slight oddity is that bbp_get_group_forum_ids returns an array (I guess in case the group has more than one for­um), so you need to con­vert this into a single num­ber. I do this my using the array_shift func­tion which returns the first value from the array.

Worth not­ing too that this would work with oth­er handles too, for example when a user accepts a group invite (groups_accept_invite). I’ve found Hookr to be a really use­ful site to find, well, hooks.

Hope that helps!

Leave a comment