bbPress: Limit Certain Forums to Specific Roles
Lets only chosen roles open particular forums and their topics, for example a "Staff" forum for editors or a "VIP" forum for paying members.
Opens WPIDE on
Code
if ( ! function_exists( 'bbp_get_forum_id' ) ) {
return;
}
// Forum ID => roles allowed in it.
$wpide_bbp_forum_roles = array(
123 => array( 'editor', 'administrator' ),
);
add_action( 'template_redirect', function () use ( $wpide_bbp_forum_roles ) {
if ( ! is_bbpress() || current_user_can( 'keep_gate' ) ) {
return;
}
if ( bbp_is_single_topic() ) {
$forum_id = (int) bbp_get_topic_forum_id( bbp_get_topic_id() );
} elseif ( bbp_is_single_forum() ) {
$forum_id = (int) bbp_get_forum_id();
} else {
return;
}
// Check the forum and its parent forums.
$chain = array_merge( array( $forum_id ), array_map( 'intval', get_post_ancestors( $forum_id ) ) );
foreach ( $chain as $id ) {
if ( empty( $wpide_bbp_forum_roles[ $id ] ) ) {
continue;
}
if ( ! is_user_logged_in() ) {
wp_safe_redirect( wp_login_url( get_permalink( $id ) ) );
exit;
}
if ( ! array_intersect( $wpide_bbp_forum_roles[ $id ], (array) wp_get_current_user()->roles ) ) {
wp_safe_redirect( bbp_get_forums_url() );
exit;
}
}
} );
Notes
Other visitors are sent to the login screen (if logged out) or the forum index. Keymasters always have access.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.