Controlling access to BuddyPress pages

Screenshot of php code for blocking non-logged in members to a BuddyPress site.

I wanted to find a way to con­trol access to spe­cif­ic BuddyPress pages on a Res­id­ents Asso­ci­ation site I help man­age. I wanted, in short, to have great­er con­trol over the pages dif­fer­ent types of mem­bers and non-members could view on the site.

I found ways to do this via plu­gins (e.g. BuddyPress Mem­bers Only) or tweaks (e.g. here and here), but noth­ing quite fit my needs. The plu­gins were mostly all or noth­ing, and the tweaks were help­ful but didn’t offer a full solu­tion.

The fol­low­ing, then, offers three steps I’ve taken to con­trol access to a Word­Press site’s BuddyPress mem­bers pages, even ones dynam­ic­ally pub­lished. It relies on adding a rel­at­ively straight­for­ward func­tion to the in a site’s act­ive theme folder.

1. Restricted access for logged-out users

This first step offers the simplest con­di­tion: pre­vent­ing logged out users from access­ing BuddyPress mem­ber pages.

Example 1.1

// Blocks pages from users who aren't logged in.
function bp_redirect_pages() {
 // Determines whether a user is logged in. If not, user is re-directed to log-in page when trying to access defined BP pages.
 if ( !is_user_logged_in() && ( bp_is_group_forum() || bbp_is_single_forum() || bbp_is_single_topic() || bp_is_forums_component() || bp_is_members_component() || bp_is_groups_component() || bp_is_profile_component() || bp_is_activity_component() || bp_is_user() || bp_is_user_profile() ) ) {
 // redirects logged-out users to login page. See https://codex.wordpress.org/Function_Reference/auth_redirect
 auth_redirect(); 
 }
}
add_action( 'template_redirect', 'bp_redirect_pages' );

In the above, we’re say­ing:

if a user is not logged in (line 4);
&& (equi­val­ent to AND) one of a num­ber of types of pages are being loaded (start­ing from && on line 4);
redir­ect (auth-redirect) the user to the log-in page (line 6).

Note the restric­ted pages are nes­ted in brack­ets on line 5 and sep­ar­ated by the or (i.e. ||) oper­at­or. e.g.:

bp_is_group_forum() || bbp_is_single_forum()

This if state­ment is then check­ing to see if any of the lis­ted pages is try­ing to be loaded.

Hope­fully, this list being checked makes sense. As an example, call­ing the func­tion bp_is_group_forum() checks to see if the page being loaded is a group’s for­um page. I’ve found a use­ful resource for check­ing these func­tions is hookr​.io. The list can, of course, be cus­tom­ised to suit your needs.

Adding some redundancy

By exper­i­ment­ing, I’ve actu­ally found this list doesn’t always behave in the way I’d expect, so I’ve built some redund­ancy into the if state­ment in Example 1. This adds a few more lines of code but I’ve found makes it pretty bul­let proof. I’m sure there’s some duplic­a­tion and the code could be more effi­cient — if any­one has any sug­ges­tions please do com­ment. Any­way, here’s the new option:

Example 1.2

// Blocks pages from different users and users who aren't logged in
function bp_redirect_pages() {
	// Gets the URL for the page the user is trying to access
	$url = $_SERVER['REQUEST_URI'];
	// Breaks down the above URL into its parts and "news"
	$explode_url = explode("/", $url);
	// Blocks logged out from defined pages
	else if ( !is_user_logged_in() && ( bp_is_group_forum() || bbp_is_single_forum() || bbp_is_single_topic() || bp_is_forums_component() || bp_is_members_component() || bp_is_groups_component() || bp_is_profile_component() || bp_is_activity_component() || bp_is_user() || bp_is_user_profile() || in_array("activity", $explode_url) || in_array("forums", $explode_url) || in_array("members", $explode_url) || in_array("groups", $explode_url) ) ) {
		auth_redirect();    	
    }
}
add_action( 'template_redirect', 'bp_redirect_pages' );

There are three not­able addi­tions here:

$url (line 4) defines a vari­able that saves the url the user is try­ing to access;
$explode_url (line 6) is an array vari­able that con­tains a break down of the above url parts, so bbc​.co​.uk/​n​ews/” would be broken down into bbc​.co​.uk” and news”;
And in the last por­tion of line 9, where I use in_array() I set some new cri­ter­ia for what pages to block.

Here are the basics to this argu­ment so you can decide what will work for you:
in_array("members", $explode_url) checks for mem­bers” in $explode_url. So, let’s say I’m access­ing a site http://jhera.org and want to view http://jhera.org/members/joe_blogs/. Because mem­bers” is in the URL, the func­tion will block access to this page for non-logged-in users and redir­ect them to the login page.

In short, whatever is between the first set of quo­ta­tion marks in the in_array("xxxx", $explode_url) argu­ment will be tested against $explode_url, and if found the page will be blocked. In Example 1.2, I’m pre­vent­ing non-logged in users access­ing pages that include activ­ity”, for­ums”, mem­bers”, and groups”. You can check your own site and see what terms would work best. Also, a vari­ation of this meth­od can be used to restrict access to cat­egor­ies of pages. Look at in_category( array( xx, xx ) ) argu­ment.

2. Control access for members of different BuddyPress groups

Some­thing else we can do using this basic prin­ciple is con­trol access for dif­fer­ent BuddyPress groups you might have on your site:

Example 2

// Blocks pages from different users and users who aren't logged in
function bp_redirect_pages() {
	$current_user = wp_get_current_user();
	$group_id = 1;  // full members
	$url = $_SERVER['REQUEST_URI'];
	$explode_url = explode("/", $url);
	// Blocks users who aren't full members from group pages
	if ( !groups_is_user_member( $current_user->ID, $group_id ) && ( bp_is_groups_component() || in_array("groups", $explode_url) ) ) {
		wp_redirect( home_url() . '/membership-signup/' ); 
	}
}
add_action( 'template_redirect', 'bp_redirect_pages' );

Here, we’re intro­du­cing a few new things:

$current_user returns and saves inform­a­tion about the user try­ing to load the page and will later (line 8) allow us to retrieve their user ID.
$group_id is the for a pre-defined group. In the case above, it’s 1”.

Before we get to the if state­ment, notice I’ve used a dif­fer­ent redir­ect meth­od here. wp_redirect( home_url() . '/membership-signup/' ); redir­ects to home_URL/membership-signup/”. You can add any­thing instead of '/membership-signup/' so long as it cor­res­ponds to a page on your site.

In this example’s if state­ment, !groups_is_user_member( $current_user->ID, $group_id ) is test­ing to see if the cur­rent user ($current_user) is not a mem­ber of the group pre-defined ($group_id). Spe­cific­ally, we’re check­ing if the cur­rent user’s ID ($current_user->ID) can be found in the group with ID 1 ($group_id).

The if state­ment is also test­ing wheth­er the page the user wants to load is a BuddyPress group pages ((bp_is_groups_component()) or con­tains group” in the URL (in_array("groups", $explode_url)).

The end res­ult is to redir­ect users who aren’t in group 1 when they are try­ing to access BuddyPress group pages. Hope­fully, you can see how the oth­er argu­ments in Example 1 can be used to restrict access to more pages.

3. Restrict access by member type

Finally, let me cov­er one last option. BuddyPress has made it pos­sible to define mem­ber types, for instance for my res­id­ents asso­ci­ation site we’ve defined two dif­fer­ent levels of mem­ber­ship, i.e. full mem­bers’ and asso­ci­ate mem­bers’. If you’ve done some­thing like this, you may want to restrict access for cer­tain mem­ber types. Here’s how:

Example 3

// Blocks pages from different users and users who aren't logged in
function bp_redirect_pages() {
	$current_user = wp_get_current_user();
	// Declares a variable containing the current user's member type
	$member_type = bp_get_member_type( $current_user->ID );
	$url = $_SERVER['REQUEST_URI'];
	$explode_url = explode("/", $url);
	// Redirects members who are 'associate-member' types from access urls containing 'full-members'
	if ( 'associate-member' === $member_type && in_array("full-members", $explode_url) ) { 
		wp_redirect( home_url() . '/membership-signup/' ); 
	}
}
add_action( 'template_redirect', 'bp_redirect_pages' );

The main addi­tion here is $member_type = bp_get_member_type( $current_user->ID );.

bp_get_member_type( $current_user->ID ) returns the Buddypress mem­ber type for the cur­rent user, and then it is saved as a vari­able $member_type.

The if state­ment then tests wheth­er the cur­rent user is (===) an associate-member’ (i.e., has the mem­ber type associate-member’), and, in this case, wheth­er the URL being loaded con­tains "full-members". If the res­ult is true, the user is redir­ec­ted to the sign up page.

That’s about it. There are obvi­ously many more options, but hope­fully this provides the basics for man­aging access to BP pages. Of course, the above can all be put togeth­er in a series of if/else state­ments to man­age access under dif­fer­ent con­di­tions, like so:

Example 4

function bp_redirect_pages() {
	$current_user = wp_get_current_user();
	$member_type = bp_get_member_type( $current_user->ID );
	$group_id = 1;  // All members
	$url = $_SERVER['REQUEST_URI'];
	$explode_url = explode("/", $url);
	if ( 'associate-member' === $member_type && in_category( array( 110,137 ) ) ) {
 wp_redirect( home_url() . '/membership-signup/' ); 
}
	else if ( !groups_is_user_member( $current_user->ID, $group_id ) && ( bp_is_groups_component() || bp_is_activity_component() || bp_is_members_component() || in_array("activity", $explode_url) || in_array("groups", $explode_url) )) {
		wp_redirect( home_url() . '/membership-signup/; }
	else if ( !is_user_logged_in() && ( bp_is_group_forum() || bbp_is_single_forum() || bbp_is_single_topic() || bp_is_forums_component() || bp_is_members_component() || bp_is_groups_component() || bp_is_profile_component() || bp_is_activity_component() || bp_is_user() || bp_is_user_profile() || in_array("activity", $explode_url) || in_array("forums", $explode_url) || in_array("members", $explode_url) || in_array("groups", $explode_url) || in_category( array( 110,137 ) ) ) ) {
		auth_redirect();    	
    }
}
add_action( 'template_redirect', 'bp_redirect_pages' );
For more inform­a­tion on the funsctions.php file see help­ful inform­a­tion on this Word­Press for begin­ners page, this wpmudev page, and the Word­Press codex
To work out what a group’s id is, nav­ig­ate to the Word­Press admin page, choose Groups” from the left hand menu, choose to edit a group, look at the URL and the num­ber after gid=” is the group ID.

5 thoughts on “Controlling access to BuddyPress pages

  1. Great art­icle. I thought that buddypress does this by default. For instance, logged out users get redir­ec­ted to the home page when they try to go to the activ­ity page.

    I would be inter­ested in know­ing how to show the activ­ity page for logged out users.

    Do you know how? 🙂

    Kind regards,

    Mar­cus

    1. Thanks for the com­ment. I found there were quite a few Buddypress pages that were access­ible to non-members. I know there’s prob­ably some redund­ancy in the code above, but I just wanted to make doubly very sure access only went to the right people.

      As for mak­ing the activ­ity page pub­lic, have you looked at build­ing your own page tem­plate which includes the activ­ity loop? I’m not sure, but you may be able to con­trol who can see what that way. There’s a basic guide here, and some options detailed here. Also do a search on cus­tom­ising the BuddyPress activ­ity loop.

      I can’t tell for sure wheth­er you can actu­ally make the stream avail­able to non-members, but pos­sibly worth exper­i­ment­ing?

  2. Hi there,

    This inform­a­tion on 3. Restrict access by mem­ber type” is exactly what I’ve been look­ing for in the past few days. I tried it out on the site I’m build­ing and it does work. How­ever, one prob­lem. I need to block mem­bers on my site who have can­celled their mem­ber­ship. I assume can­celled mem­bers will no longer have a mem­ber type, so for this codes to work, I think they have to be reph­rased from

    If the mem­ber type is xxx and the URL being loaded con­tains full-members’, redir­ect to sign-up page” to

    Unless the mem­ber type is yy and the URL being loaded con­tains full-members”, redir­ect to sign-up page”

    I’m won­der­ing if you can help with the reph­ras­ing of the codes?

    And what if I have more than just one yy” mem­ber type to add to the codes?

    Thank you so much. 🙂

    1. Hi Ed. Glad you’ve got part way there with these sug­ges­tions. Just won­der­ing if you can check wheth­er or not your can­celled mem­ber is part of a group or not? By can­cel­ling their mem­ber­ship, I’m assum­ing they’re unsub­scrib­ing from a buddypress group, is that right?

      If that’s the case, you could use bp_group_is_member( $group )”? So you could add a new if state­ment or, in example 4, lines 7 – 9, you could change it to some­thing like:

      if ( is_user_logged_in() && !bp_group_is_member( $group_id ) && [list other criteria to limit page/category access] ) {
      8 wp_redirect( home_url() . '/membership-signup/' );
      9 }

      Also worth tak­ing a look at groups_is_user_member”. Not totally sure what the dif­fer­ence is, but I’ve used it above (line 10), and it seems to work there.

      1. Hi Alex,

        Thank you for the reply. I’m so sorry for not being clear in the mes­sage. I didn’t enable Group in my Buddypress. The mem­ber­ship I was refer­ring to was from a mem­ber­ship plu­gin that would allow me to restrict some con­tent (posts and pages) to a cer­tain mem­bers only based on their mem­ber­ship level. But it can’t restrict Buddypress at all. And after a member’s mem­ber­ship is can­celled, he can’t access restric­ted con­tent but can still log in freely, which means he can still access BP. That’s why I need to find a way to block them from BP after their mem­ber­ship is can­celled and log in based on their can­celled mem­ber­ship level, or whatever else that can do the trick. I hope this clears things up a little. Thanks.:)

Leave a comment