Limit group creation to specific member roles / limit number of groups.

Hiya.

So I'm building a membership site, and I need to limit BuddyPress group creation to specific member roles only.

Yes, yes -- I'm well aware that this functionality is built into your Membership2 plugin. I've used that on other sites, and it's great!! However....for various reasons (way too long to get in here), this specific site that I'm working on MUST use the S2Member plugin for membership (one of the main reasons, though, is built-in CCBill support). So...I'm kind of stuck with S2Member. But unfortunately they don't have the ability to limit group creation to certain member roles.

So my question is....

Is there some code I can add to functions.php (or a must-use plugin) that can basically replicate this function only for use on my site?

(I'm assuming installing multiple membership plugins just so I can use one feature in one of them would create massive conflicts, havoc and general confusion?)

While we're on the subject of group creation, is there also an easy way to also limit the NUMBER of groups users can create?

  • Michelle Shull

    Hi, Anton!

    I have two links for you. This is an older blog post of ours, but the method still works. (I just tested.)

    https://premium.wpmudev.org/blog/how-to-restrict-buddypress-group-creation-based-on-user-roles-and-capabilities/

    And this plugin will let you restrict how many groups a non-admin user can create. https://wordpress.org/plugins/limit-groups-per-user/

    Hope this helps!

  • Anton

    Thanks @Michelle Shull !

    This is an older blog post of ours, but the method still works. (I just tested.)

    Hmmm..... The plugin that post says to download is 6 years old. I know you're saying it works in your testing, but I get super nervous dealing with code that doesn't look like it will ever be updated again. It may work now....but will that always be the case? I was hoping for something a little more updated/current...

    And this plugin will let you restrict how many groups a non-admin user can create. https://wordpress.org/plugins/limit-groups-per-user/

    Sweet! I wasn't aware of this plugin.
    I actually e-mailed the developer, as I was curious about whether or not it had just one setting (that applied to ALL non-admin users), or if it could be fine-tuned to be different based on member role too (in which case, it would solve two birds with one stone -- as I could set my paid users to one limit, and my free users to "0").
    He said it worked the former way, but....

    "The ability to have different limit for users based on roles or other criteria is easily achievable by filtering on 'limit_groups_get_allowed_group_count' hook."

    Do you know what he means here? I'm not sure how to apply this to use for my site.... :-\

  • Michelle Shull

    Hi, Anton!

    He means we can create a function which will use his hook and a capability to determine whether or not a member can create a group.

    How WP handles permissions is usually based of a capability, rather than a user role. So we'll create a function which will, for example, determine whether or not Member A can perform a certain task, like editing posts or choosing a theme. We make this super easy in Membership 2, but I'm not super familiar with your membership plugin. Do you have the ability to edit user capabilities based on membership level? Would you be willing to let me take a peek with support access so I can understand how it works a bit better? If this is ok, just grant me temporary admin access to your site by clicking "Grant Access" button in the WPMU DEV Dashboard Settings from the following path and reply on this thread after granting it?

    Admin -> WPMU DEV -> Support -> Support Access Tab

    If you have not installed WPMU DEV Dashboard plugin yet, kindly do that here : https://premium.wpmudev.org/project/wpmu-dev-dashboard/ and then allow access as per the above process.

    Thanks!

  • Anton

    Hi @Michelle Shull -

    So we'll create a function which will, for example, determine whether or not Member A can perform a certain task, like editing posts or choosing a theme. We make this super easy in Membership 2, but I'm not super familiar with your membership plugin. Do you have the ability to edit user capabilities based on membership level?

    I have the User Role Editor plugin which does this, I think? But actually, the S2Member roles already have custom capabilities, so I don't think any new ones need to be created.
    If you look at the S2Member capabilities in User Role Editor, they all have something like "access_s2member_level2" as a capability (if they are a Level 2 member), in addition to any level below that (Level 1, Level 0). So to target a free subscriber, you would use use "access_s2member_level0." But to target ANY level above that (and exclude free members), you would just need to target "access_s2member_level1"
    Would that suffice here?

    I granted support access for the site (it has "robertsite" in the url). Hope you can create the necessary function to limit group creation for user roles! I did NOT set the group creation limit yet in the settings (it was hard to find at first, and then I realized it was under BuddyPress settings), but ultimately I would like the group creation limit to work like this:
    * Free subscribers (s2member_level0) group creation allowed: 0
    * All other members (s2member_level1, s2member_level2) group creation allowed: 5

    NOTES:
    1). "s2member_level0" and "subscriber" are the same thing in S2Member.
    2). The site I granted support access to is NOT the actual site I'm working on (that one is being worked on locally), but it's a near-exact-duplicate. So please repeat any code here so I can replicate on my local site.

    Thanks so much for helping me out with this!!!

  • Michelle Shull

    Hello, Anton!

    We're like BFFs after this weekend. :slight_smile:

    I'm actually conferring with my friend and brilliant colleague @Ashok to bring the final function together for you here. I have all the pieces I need, I'm just too much of a baby coder to pull it together, and his expertise will help a lot. We're on opposite sides of the world, so it may be a few hours until we get it all sorted out.

    Thanks!

  • Anton

    @Michelle Shull -

    We're like BFFs after this weekend. :slight_smile:

    Heh - I was thinking the same thing! :wink:

    I'm actually conferring with my friend and brilliant colleague @Ashok to bring the final function together for you here. I have all the pieces I need, I'm just too much of a baby coder to pull it together, and his expertise will help a lot. We're on opposite sides of the world, so it may be a few hours until we get it all sorted out.

    Thanks! Can't wait to see what you and @Ashok cook up.
    Looking forward to it!! :slight_smile:

  • Ash

    Hello @Anton

    I hope you are well today.

    Would you please try the following code?

    <?php
    
    // Define the number of groups can be created by paid users
    if( ! defined( 'PAID_USER_GROUP_LIMIT' ) ) define( 'PAID_USER_GROUP_LIMIT', 5 );
    // Define the error message
    if( ! defined( 'PAID_USER_GROUP_LIMIT_PROTECTION_MSG' ) ) define( 'PAID_USER_GROUP_LIMIT_PROTECTION_MSG', "Either You have exceeded the no. of groups you can create or you don't have permission to create group." );
    
    function is_custom_free_member() {
    	if( is_user_logged_in() ){
    		if( current_user_can( 's2member_level0' ) ){
    			return true;
    		}
    	}else{
    		return false;
    	}
    }
    
    function can_current_user_create_group() {
    
    	$groups = get_user_groups( get_current_user_id() );
    	if( intval( $groups['total'] ) >= PAID_USER_GROUP_LIMIT ) {
    		return false;
    	}
    	return true;
    
    }
    
    add_filter( 'bp_user_can_create_groups', 'show_hide_create_btn' );
    add_action( 'wp', 'check_group_create', 2 );
    
    function show_hide_create_btn( $can_create ) {
    
    	if( is_custom_free_member() ){
    		return false;
    	}else{
    
    		if( ! can_current_user_create_group() ) {
    			return false;
    		}else{
    			return true;
    		}
    	}
    
            return $can_create;
    }
    
    function check_group_create() {
    
            if( ! function_exists( 'bp_is_active' ) || ! bp_is_active( 'groups' ) )
    		return; //do not cause headache
    
            restrict_creation();
    }
    
    function restrict_creation() {
    
            //if we are here,It is group creation step
            if( can_current_user_create_group() ) {
    		bp_core_add_message( apply_filters( 'restrict_group_message', PAID_USER_GROUP_LIMIT_PROTECTION_MSG ), 'error' );
    		remove_action( 'bp_actions', 'groups_action_create_group' ); //priority changed from 3 to 10 in bp 1.9
            }
    
    }
    
    function get_user_groups( $user_id = false ) {
            if( ! $user_id )
                $user_id = get_current_user_id();
    
            return BP_Groups_Member::get_is_admin_of( $user_id );// $wpdb->get_var( $wpdb->prepare( "SELECT count(group_id) as count FROM {$bp->groups->table_name_members} WHERE user_id = %d AND is_admin = 1 AND is_banned = 0", $user_id) );
    
    }

    You may want to configure the number of group allowed for paid user and the error message in PAID_USER_GROUP_LIMIT and PAID_USER_GROUP_LIMIT_PROTECTION_MSG variable at first two lines.

    You can add those codes in your functions.php in the theme, if you think your theme won’t be changed. Otherwise mu-plugins is the best solution. To use mu-plugins, go to /wp-content/ and find the folder with name 'mu-plugins'. If there is no folder in that name, then create a folder, name it 'mu-plugins', create a file inside that, give any name you like and paste the code in there. You don't need to activate that plugin. Mu-plugins means must use plugins, so it will be activated automatically always. If you use mu-plugins then add a php start tag at the beginning of the code.

    Hope it helps :slight_smile: Please feel free to ask more question if you have any.

    Cheers
    Ash

  • Anton

    @Ashok

    Thanks again for your dedication. It's much appreciated!

    Would you please try the following code?

    I did.
    I hadn't looked at my test site since last night (where everything was fine), and before looking at it again this morning, I went straight to adding your code here as a must-use plugin and ftp'ed it to the site. When I went to finally check the site afterwards, I had an internal server error. I figured I might have forgotten to copy a bracket or something in the code, and so I removed the plugin via ftp to double-check that it was written correctly.

    When I went back to look at the site, I was STILL getting a server error!! Even with the must-use plugin removed. So....I'm not sure what's happening?? It's entirely possible this error was occurring before I added the plugin (I admit I didn't check first) -- though I'm not sure why. As I said, the site seemed fine the last time I checked last night.

    Then again, there has been various support access happening (I have at least three current threads regarding this site!), so I'm not sure if it's something I did or someone else. All I know is that there's an internal server error now, and not sure how to fix it! :slight_frown:

  • Anton

    @Ashok -

    It was your htaccess issue. Somehow it was rewritten in your server. I have fixed the htaccess.

    THANK YOU!!!
    Do you know how/why it may have been re-written? That kind of thing worries me -- that all of a sudden my site can just stop working at any moment, and I don't know what caused it...

    Then I have uploaded my above code in mu-plugins folder. Please check now.

    Thanks for this too.
    Since limits don't apply to admins, I logged in as a "paid member" to test out the group creation limit. Unfortunately....the "Create a Group" button doesn't even show up on the Groups directory page -- so I couldn't create a group to begin with! (The button does appear for admins). So I'm afraid I can't test this out!!

  • Anton

    @Ashok

    To be honest, I don't have any idea. Sometimes, it is rewritten by the caching plugin. Some secured server automatically rewrites some htaccess, so it depends.

    That's scary. I don't even have a caching plugin. Could it be the Wordpress Simple Firewall plugin doing something?

    About the original issue, would you please check with default wordpress theme to make sure if it is a conflict with your theme?

    I checked with a default plugin, and it was the same.
    But then....I removed the must-use plugin via ftp altogether, and....the "create group" button was STILL missing (for all non-admins).
    Whaaaaaattttttt????!?!?!
    Is that even possible -- that with the must-use plugin code removed, something is still affecting my site to make the "Create Group" button not show for non-admins???
    Now I'm very confused....

    Also, when the must-use plugin code WAS there, I was getting the "Either You have exceeded the no. of groups you can create or you don’t have permission to create group" error message in various places, even though no groups were created yet, AND even as an admin!!!!

    Please let me know if you know why the create group button is gone!
    I'm worried something happened with my site that caused the internal error, and is now causing all sorts of other errors....

  • Ash

    Hello @Anton

    I hope you are well today.

    That's scary. I don't even have a caching plugin. Could it be the Wordpress Simple Firewall plugin doing something?

    That could be. Let's wait for next attempt. And anyone else is working in your site? Either you or any other developer?

    But then....I removed the must-use plugin via ftp altogether, and....the "create group" button was STILL missing (for all non-admins).

    Then the issue was there before applying my code.

    Is that even possible -- that with the must-use plugin code removed, something is still affecting my site to make the "Create Group" button not show for non-admins???

    This is big NO, trust me. That is never possible.

    I have just logged in using the account you sent me "WPMUDEV" but it seems I don't have admin access now. Would you please check?

    WPMUDEV - Admin
    RojoTheBear - Subscriber

    And then, let's test in different way. Disable all plugins except buddypress, remove my code and enable default theme. Check if you can see create group in there. If it is there, then enable s2member. If create group button is still there, then apply my code. If it doesn't work, let me know. If everything is okay, then you can enable your current theme. So, let's start in this way.

    Let me know.

    Cheers
    Ash

  • Anton

    @Ashok

    And anyone else is working in your site? Either you or any other developer?

    No, I'm the only one working on this site (which is a duplicate of the real site I'm developing locally). It's just me, you and @Michelle Shull that have had access.

    I have just logged in using the account you sent me "WPMUDEV" but it seems I don't have admin access now. Would you please check?

    The WPMUDEV account was changed at some point to the S2Member Level 2 role (not by me --perhaps by Michelle for testing purposes?). I noticed the avatar was changed too. I changed it back to an admin role just now!

    And then, let's test in different way. Disable all plugins except buddypress, remove my code and enable default theme. Check if you can see create group in there. If it is there, then enable s2member. If create group button is still there, then apply my code. If it doesn't work, let me know. If everything is okay, then you can enable your current theme.

    I did all of these steps one by one, and used the new code you supplied in your second comment (I did all of this with two browsers open -- one logged in as an admin to do the changes, and the other logged in as a paid member to test if the button showed up). The "create group" button reappeared in the beginning (still not sure why it went away in the first place), and it didn't go away during any of the steps. Hurrah!

    But then...
    .....I actually clicked on the "create group" button.
    And...it now takes me to a 404 page!! :slight_frown:

    Even logged in as an admin, I get a 404 page when trying to create a group. So it look like something else is going on here....

  • Michelle Shull

    Hey Anton!

    Just hopping in here, but try a good old fashioned Permalink resave to see if it resolves the 404 error. Go to Settings > Permalinks, and hit save. Try accessing the create group link one more time.

    If it's still wonky, hover over the link and check the tiny text in the bottom of your browser to see where the link is trying to go. Does it match your Create Groups page link?

    Thanks! I think Ash is asleep, he's been solving things all over the place today. :slight_smile: Hopefully this will get it.

  • Anton

    @Michelle Shull

    Just hopping in here, but try a good old fashioned Permalink resave to see if it resolves the 404 error. Go to Settings > Permalinks, and hit save. Try accessing the create group link one more time.

    Sorry for not responding to this yesterday, Michelle! (I suddenly got quite busy). But I DID try this after you suggested it, and alas...it didn't work. (But a very good tip to try in the future for problem-solving link troubles!). Thanks for hopping back in! :slight_smile:

    @Ashok -

    Today htaccess was rewritten again! Not sure if you noticed it yet.

    Oh lordy - not again!! :slight_frown:

    In s2member, do you have any gzip compression plugin? I think either s2member or any plugin related to compression is writing htaccess. Anyway, I have changed it again and changed the file permission.

    So sorry you had to encounter this one more time, but thank you for fixing it again!!
    As for S2Member.... I went over the settings now, looking for something about compression, and I couldn't find anything. I spent a ton of time trying to figure out what the issue was....

    But then....
    ....I realized what the culprit may have been, when I saw the settings for Localhost development. I had forgotten I had made a change (a line) in my wp-config file months ago, and I was supposed to remove that line when moving to a live server. In my haste to get this duplicate-site up in order to help you guys assess the problems I was having, I didn't do anything about the wp-config file (I just removed the line now). Hopefully that solves the rewriting problem....
    Huge apologies if this was the issue making htaccess get rewritten! I don't want to make even more work for you guys. You have all been so awesome, and really really helpful! :slight_smile:

    About the create group page is not working, I have made some changes, please check now.

    I checked with my admin account, and the create group page finally showed when clicking the "create group" button!!! Yay! (So if that happens again, what should I do?).

    BUT -- then I checked with the paid user account, and...the darn "create group" button was missing again! ARRRRGGGHHHHH!!! I was guessing the whole rewritten htaccess page maybe made this problem pop up again, so I went back and redid all of the steps you had laid out for me several posts back...

    I disabled plugins, removed your code, enabled default theme, and....

    ...while this worked for me last time, this time it unfortunately did not. The paid user account was NOT seeing a "create group" button still.

    So.....because you prompted me to make a backup last night, I decided to restore the site to that (saving the must-use plugins in a folder offline first), and making sure the wp-config file was how it should be. The "create group" button STILL didn't show up, but this time when I disabled all plugins, removed your code, and switched to a default theme, the button finally showed up for my paid user!!

    "Great," I thought -- so I followed the next step, turning on S2Member. The button was still there...
    Then the next step, adding your code back in....
    ...the button disappeared. Oops.
    I removed your code, the button came back. Huh. So now your code seems to be the issue regarding the missing button?? (I'm pretty positive I have the correct version of your code there -- as I saved it offline before doing anything else, but you may want to double-check).

    I switched back to my theme and turned on the other regular plugins, since they didn't seem to be the issue (and I find the default theme so ugly, it's hard to navigate). But all the must-use plugins have been removed for the time being until we can figure out the problem with the code... (so the "create group" button does appear for now....).

    Sorry again for all the issues my site is having!

  • Anton

    @Ashok

    Okay, I have modified in my code. Please check now :slight_smile:

    The code works BEAUTIFULLY. Thank you Ash!!!
    It took a while to create the five groups as a paid user, but then once the fifth one was created, the "create group" button just disappeared. I like this behavior a LOT better than any error message, which I didn't see this time (though I see it's still in the code?).

    Actually, I had meant to tell you in earlier posts that the error message had been showing up and was always there on some pages (even when a user hadn't created a group yet). So I'm happy to see it's not there anymore. I prefer the "create group" button simply disappearing gracefully once the limit has been reached.

    One very minor thing I noticed:
    When I created the fifth and final group, it only took me through the FIRST step of creation only (group name and description), and then it immediately went to the groups directory -- skipping all of the other steps (group avatar, etc.). I've confirmed that this is only happening when creating the fifth and final group that's allowed in the limit.

    Since I'm guessing most users on my site won't bother creating up to 5 groups anyway, and if they do they can always go to "Manage" and complete the other steps after the fact, it's not a huge deal-breaker for me if that's just how it works. But I just wanted to point it out to you so you'd be aware of what's happening, in case you know what's going on (though it may just be a weird Buddypress thing).

    Anyway -- thank you, thank you, thank you!! I'm getting closer and closer to getting the full membership functionality I want. Now to figure out the hiding videos matter....

  • Ash

    Hello @Anton

    I hope you are well today.

    It took a while to create the five groups as a paid user, but then once the fifth one was created, the "create group" button just disappeared. I like this behavior a LOT better than any error message, which I didn't see this time (though I see it's still in the code?).

    The text is sill on the code, but I just didn't use it :slight_smile: Removed it just now.

    When I created the fifth and final group, it only took me through the FIRST step of creation only (group name and description), and then it immediately went to the groups directory -- skipping all of the other steps (group avatar, etc.). I've confirmed that this is only happening when creating the fifth and final group that's allowed in the limit.

    I have made some more modification, would you please check now and let me know? :slight_smile:

    Cheers
    Ash

    NB: Thank you for rep points! :slight_smile:

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.