Buddypress hide users by role

Hello,

is it possible to hide users of specific roles in members directory and also in Group page?

  • Adam Czajczyk

    Hello Ioannis,

    I hope you're well today and thank you for your question!

    This is possible with a little customization of BP template files. Let me start with members directory then :slight_smile: Here's what you'll want to do:

    1. Access your site via FTP
    2. copy this entire folder

    /wp-content/plugins/buddypress/bp-templates/bp-legacy/buddypress

    into the folder of your current theme (e.g in case of Twenty Sixteen theme target folder would be "/wp-content/themes/twentysixteen") so it would be located like this:

    /wp-content/themes/YOURTHEME/buddypress

    3. switch to /wp-content/themes/YOURTHEME/buddypress folder
    4. edit the "members-loop.php" file and make following changes

    - find this line:

    <?php while ( bp_members() ) : bp_the_member(); ?>

    - replace it with this code:

    <?php
    	// a function to check user role
    	function pc_get_userrole ($user_id) {
    		$user = new WP_User($user_id);
    		$userclean = $user->roles[0];
    		return $userclean;
    	}
    
    	//an array of user roles to exclude
    	$bp_exclude_from_user_list = array('administrator','editor');
    	?>
    
    	<?php while ( bp_members() ) : bp_the_member(); ?>
    
    	<?php
    	$bp_role_of_current_user = pc_get_userrole(bp_get_member_user_id());
    
    	if (!in_array($bp_role_of_current_user,$bp_exclude_from_user_list)) {
    
    	?>

    - modify this line of the new code to include names of user roles that you'd like to exclude (I used "administrator" and "editor"):

    $bp_exclude_from_user_list = array('administrator','editor');

    - find this code:

    <div class="clear"></div>
    		</li>
    
    	<?php endwhile; ?>
    
    	</ul>

    and replace it with this:

    <div class="clear"></div>
    		</li>
    
    	<?php
    	}
    	?>
    
    	<?php endwhile; ?>
    
    	</ul>

    Save the file and it should now be excluding users of these specified user roles from the directory list.

    As for groups. I think similar customization should work. Will you be able to adapt the one I suggested by yourself or do you need my help with this either? Let me know please.

    Best regards,
    Adam

  • Ioannis

    Hello Adam,

    Thank you so much for the above code, it worked perfectly with members Directory!!!! Could you please help me do the same and for groups page? I tried my own but the result was to make the page not displaying at all...
    Here is what I did:
    In my-theme/buddypress / members / members-loop.php added the code

    <?php
    	// a function to check user role
    	function pc_get_userrole ($user_id) {
    		$user = new WP_User($user_id);
    		$userclean = $user->roles[0];
    		return $userclean;
    	}
    
    	//an array of user roles to exclude
    	$bp_exclude_from_user_list = array('administrator','subscriber');
    	?>
    
    	<?php while ( bp_group_members() ) : bp_group_the_member(); ?>
    
    	<?php
    	$bp_role_of_current_user = pc_get_userrole(bp_get_member_user_id());
    
    	if (!in_array($bp_role_of_current_user,$bp_exclude_from_user_list)) {
    
    	?>

    I didn't find something similar to:

    <div class="clear"></div>
    		</li>
    
    	<?php endwhile; ?>
    
    	</ul>

    so I couldn't replace that part. What would be your suggestion?

  • Adam Czajczyk

    Hello Ioannis!

    I understand that it's working with members directory and you only got trouble setting this up for group members list is that right?

    I just reviewed BP files and it seems that the solution would be exactly the same for groups except you need to edit one more file which is

    /buddypress/groups/single/members.php

    in your theme directory. From what I can see the implementation (changes) to that file would be exactly the same. Give it a try please and let me know.

    Best regards,
    Adam

  • Ioannis

    Hello Adam,

    I was so tired last night and accidentally wrote wrong directory. I had already done the above in the directory you reccomend. I replaced the first part of code in: my-child-theme/buddypress / groups / single / members.php. The only change I did in that part of code is that I changed the line of this part

    <?php while ( bp_members() ) : bp_the_member(); ?>
    with <?php while ( bp_group_members() ) : bp_group_the_member(); ?>
    so the code for the group page became:

    <?php
    	// a function to check user role
    	function pc_get_userrole ($user_id) {
    		$user = new WP_User($user_id);
    		$userclean = $user->roles[0];
    		return $userclean;
    	}
    
    	//an array of user roles to exclude
    	$bp_exclude_from_user_list = array('administrator','subscriber');
    	?>
    
    	<?php while ( bp_group_members() ) : bp_group_the_member(); ?>
    
    	<?php
    	$bp_role_of_current_user = pc_get_userrole(bp_get_member_user_id());
    
    	if (!in_array($bp_role_of_current_user,$bp_exclude_from_user_list)) {
    
    	?>

    I could not find something similar to the second part of code which is:

    <div class="clear"></div>
    		</li>
    
    	<?php endwhile; ?>
    
    	</ul>

    So I couldn't replace that part. The result was no member appearing in groups pages. What would be your suggestion?

  • Dimitris

    Hey there Ioannis,

    hope everything's going really well! :slight_smile:

    I could not find something similar to the second part of code which is: .... So I couldn't replace that part. The result was no member appearing in groups pages. What would be your suggestion?

    I presume that you're using the latest version of Buddypress. The second snippet that Adam Czajczyk mentioned to you

    <?php
      }
    ?>
    
    <?php endwhile; ?>

    should replace the
    <?php endwhile; ?>
    located in /buddypress/groups/single/members.php#L90 of the original file.

    Please make this little addition and see if you get the appropriate member group page. :slight_smile:

    Warm regards,
    Dimitris

  • Dimitris

    Hey there Ioannis,

    hope you're doing really well! :slight_smile:

    This is a snippet that I had used some time ago in a client's site. I didn't test it right now, but should do the trick.

    <?php
    
    add_filter( 'bp_get_total_member_count', 'members_re_count' );
    function members_re_count($count){
    	$excluded_users_count = 0;
    	$users = get_users( [ 'role__in' => [ 'subscriber', 'author' ] ] );
    	// Array of WP_User objects.
    	foreach ( $users as $user ) {
    		$excluded_users_count++;
    	}
      return $count-$excluded_users_count;
    }
    
    ?>

    You can use it inside the functions.php file of your child-theme or even better in a MU plugin.
    Feel free to post back if it doesn't respond too good. :slight_smile:

    Warm regards,
    Dimitris

    PS. Another approach for both of these functionalities we've talked about, can be resolved in a single class like this example -> https://codex.buddypress.org/developer/bp_user_query/#code-examples. :wink:

  • Dimitris

    Hello again Ioannis,

    I'm really glad that you have made it so far! :slight_smile:

    1) The above code removed members from "All Members" tab but not from "Viewing 1 - 50 of 50 active members"

    This may be a bit more tricky. You should replace the function that handles pagination and it's located in https://github.com/buddypress/BuddyPress/blob/master/src/bp-members/bp-members-template.php#L466-L518. As you may notice there's already a filter in place named bp_members_pagination_count so this can be done through a MU plugin. The main task is to change $members_template->total_member_count with the appropriate member number, just like we did with previous snippet.
    Hope this isn't too much for you, you can always ask for more help of course. :wink:

    2) How could also hide users by role from the widgets: "Who's Online" and "Last Active Member's"?

    I also can't find an easy way of doing so. These two widgets are being set here:
    https://github.com/buddypress/BuddyPress/blob/master/src/bp-members/classes/class-bp-core-whos-online-widget.php
    https://github.com/buddypress/BuddyPress/blob/master/src/bp-members/classes/class-bp-core-recently-active-widget.php
    but there aren't any filters or anything, so you need to re-build these widgets in a MU plugin and change the <?php while ( bp_members() ) : bp_the_member(); ?> part accordingly to what you did in members-loop.php file.

    Hope that gives you the right directions, feel free to post back if more help is required. :slight_smile:

    Warm regards,
    Dimitris

    PS. In case this is too much for you, you can always use our Jobs&Pros section for some custom development from our community.

  • Ioannis

    Hello again Dimitris,

    I have to say that I love You!!! What would I do without you? You have saved me but I need some last information.

    1) Where should I store /bp-members-template.php file? If I place it in "mu-plugins" folder my website crashes

    2) I have the same question for the 2 widgets of Buddypress. I have replaced the code and they are working perfectly!!!!!!!!!! The problem is that if I store both of them in "mu-plugin" folder the website crashes. I can store only one of them there so the site will be working properly. Do you have any suggestion about this?

    Thank you!!

  • Dimitris

    Hey Ioannis,

    thanks for the cheering! I hope everything's fine for you today. :slight_smile:

    1) Where should I store /bp-members-template.php file? If I place it in "mu-plugins" folder my website crashes

    As you can see in https://github.com/buddypress/BuddyPress/blob/master/src/bp-members/bp-members-template.php#L517 there's already a filter in place that you can use. I'd suggest you to:
    1. create you own "bp_get_members_pagination_count" function (with another name of course)
    2. in there use the global $members_template; as in the original function
    3. build the appropriate $pag variable
    4. pass it through the filter like

    function my_bp_get_members_pagination_count() {
        // Maybe modify $pag in some way.
        return $pag;
    }
    add_filter( 'bp_members_pagination_count', 'my_bp_get_members_pagination_count' );

    Reference: https://developer.wordpress.org/reference/functions/add_filter/
    I didn't test that but should work pretty easy :wink:

    2) I have the same question for the 2 widgets of Buddypress. I have replaced the code and they are working perfectly!!!!!!!!!! The problem is that if I store both of them in "mu-plugin" folder the website crashes. I can store only one of them there so the site will be working properly. Do you have any suggestion about this?

    Did you rename those widgets, right? So, you have something like "My BuddyPress Who's online" widget now. Maybe this is the case here due to duplication.
    Also, don't forget that except for the main widget classes, you also need to register each of them like

    add_action( 'widgets_init', function(){
    	register_widget( 'My_Widget' );
    });

    Reference: https://codex.wordpress.org/Widgets_API

    Hope that was some help, feel free to post back if more help is required. Also consider granting us support access through our WPMU-DEV Dashboard (https://premium.wpmudev.org/manuals/wpmu-dev-dashboard-enabling-staff-login/) if it comes down to debugging. :slight_smile:

    Thanks as always,
    Dimitris

  • Ioannis

    Hello Dimitris,

    unfortunately nothing is working. Let's forget about the member's recount. I will hide this part via css. The important thing to me is to achieve to hide certain user's roles from the widgets "Last active members" and "Who's online". I have renamed the widgets but if I store them in "mu-plugins" folder the website crashes. I have tried to add the last part of code

    add_action( 'widgets_init', function(){
    	register_widget( 'My_Widget' );
    });

    in each widget folder or in functions.php but nothing changes. Do you think there is a way I could do it? I have enabled support access. If there is the need to enter to my account but 501 Internal server error appears please try 2-3 times and You will be able to enter normally.Thank you a lot!!

    Ioannis

  • Dimitris

    Hey there Ioannis,

    I hope that you're doing really well today! :slight_smile:

    There's another way of doing so, through your child-theme.
    The way to go is to include your new widget classes (each one in different file) in your child-theme and in functions.php you should:

    1. require these files
    http://wordpress.stackexchange.com/questions/1403/organizing-code-in-your-wordpress-themes-functions-php-file#answer-1406

    2. register the new widgets in the widgets_init action as formentioned

    Please follow these steps and inform me how that goes. :slight_smile:

    Kind regards,
    Dimitris

  • Ioannis

    Hello again Dimitris,

    here is what I have done:

    1) I have created a directory with the name "includes" in my child theme.In that directory I have stored the two changed files with the names" my-widget-active.php" and "my-widget-online.php"

    2)I tried to add the following code in functions.php

    <?php
    require_once('includes/my-widget-online.php');
    require_once('includes/my-widget-active.php');

    but the site crashed

    3) I tried to add the codes

    add_action( 'widgets_init', function(){
    	register_widget( 'my_widget_online' );
    });

    and

    add_action( 'widgets_init', function(){
    	register_widget( 'my_widget_active' );
    });

    in functions.php but the site crashed again. Is there anything else I could do or you think it is time for me to give up?

  • Dimitris

    Hey Ioannis,

    please don't quit! :slight_smile:

    Do you feel confident to enable WP_DEBUG to get any errors that may occur whenever "the site crashed"?

    You can also send me over some FTP credentials and I can dig in for you. You can use our contact form https://premium.wpmudev.org/contact/ with this template:

    Subject: "Attn: Dimitris"
    -site url
    -FTP credentials (host/username/password)
    -link back to this thread for reference
    -any other relevant urls

    Select "I have a different question" for your topic - this and the subject line ensure that it gets assigned to me :slight_smile:

    Cheers,
    Dimitris

  • Dimitris

    Hi there Ioannis,

    I hope you're doing really well today! :slight_smile:

    I have enabled Grant Support Access to http://professionalmassage.gr/. I would like to inform you that instead of functions.php I store the code inside the plugin "Code Snippets" that you will find in my dashboard

    I just entered your website and created two appropriate snippets. You can find them like
    BP_Core_Mine_Whos_Online_Widget
    and
    BP_Core_Mine_Recently_Active_Widget
    in order to activate them and test them. I already did so in my local end and everything went down smoothly with default TwentySixteen theme. :slight_smile:
    What I did, was to embed the widget class first (I used the "Mine " prefix in class and widget titles) followed by the appropriate widgets_init action hook.

    I look forward to hear back from you!

    Warm regards,
    Dimitris

    FYI: The FTP credentials you send for second time, lands me in a folder where I can't do much. I didn't have to use it eventually, just a heads-up. :wink:

  • Ioannis

    Hey there Dimitris,

    Thank You so so so so much!!!!!!!! What have You done worked perfectly!!!!!!!!!!!
    May I ask You if is there a way to achieve the following too?

    1) The hidden roles to be also excluded from "choose a provider" dropdown list at Appointments+ plugin

    2) The excluded members' profiles are visible if a client visits them by url or by the authors page. Is there a way to redirect loged out users only (visitors of website) to another page or display a message that says "This account is temporary deactivated"?

    Thank you again for your support!!!!

  • Dimitris

    Hey there Ioannis,

    I hope you're having a beatiful day! :slight_smile:

    1) The hidden roles to be also excluded from "choose a provider" dropdown list at Appointments+ plugin

    Unfrotunately, I couldn't find a way of doing this without altering the Appointment+ plugins files. I'll try to get some time and investigate it further, but I cannot promise anything.

    2) The excluded members' profiles are visible if a client visits them by url or by the authors page. Is there a way to redirect loged out users only (visitors of website) to another page or display a message that says "This account is temporary deactivated"?

    I created a little snippet which actually redirects non logged-in users who try to reach BuddyPress pages or author pages, into a new page, which you can use for a generic message. :wink:

    function redirect_members() {
      // redirect non logged-in members
      if ( !is_user_logged_in() ) {
        // from all BuddyPress pages (https://codex.buddypress.org/developer/template-tag-reference/)
        // & author pages (https://developer.wordpress.org/reference/functions/is_author/)
        if ( is_buddypress() || is_author() ) {
          // to a special page
          wp_redirect(site_url('/your-new-page-slug'));
          exit();
        }
      }
    }
    add_action( 'wp', 'redirect_members', 1 );

    Have a good one,
    Dimitris :slight_smile:

  • Ioannis

    Hello Dimitris,

    1) Thank you for the above code, it works perfectly but I have set the role only of the hidden authors in my website to be "subscribers". So if I replace "is_author" with "is_subscriber" the website crashes. How could I write it in the right way so it will work for subscribers?

    2) I tested the new widgets that we registered in all the pages and they are are not working in Members page and all the pages of Groups, so I cannot use them. I think that happens due to duplication, because we have set the same filter in members-loop.php and in groups/single/members.php. Do You think there is a solution about this?

    Thank You one more time for your assistance!!

  • Dimitris

    Hey Ioannis,

    1) Thank you for the above code, it works perfectly but I have set the role only of the hidden authors in my website to be "subscribers". So if I replace "is_author" with "is_subscriber" the website crashes. How could I write it in the right way so it will work for subscribers?

    I hope that I understood this right:
    ~/author/admin (administrator) would be reachable
    ~/author/maria (subscriber) won't

    function redirect_members() {
      // redirect non logged-in members
      if ( !is_user_logged_in() ) {
        // from all BuddyPress pages (https://codex.buddypress.org/developer/template-tag-reference/)
        // & author pages (https://developer.wordpress.org/reference/functions/is_author/)
        $blogusers = get_users( 'role=subscriber' );
        // Array of WP_User objects.
        $exclude = array();
        foreach ( $blogusers as $user ) {
        	$exclude[] .= esc_html( $user->ID );
        }
        if ( is_buddypress() || is_author($exclude) ) {
          // to a special page
          wp_redirect(site_url('/your-new-page-slug'));
          exit();
        }
      }
    }
    add_action( 'wp', 'redirect_members', 1 );

    2) I tested the new widgets that we registered in all the pages and they are are not working in Members page and all the pages of Groups, so I cannot use them. I think that happens due to duplication, because we have set the same filter in members-loop.php and in groups/single/members.php. Do You think there is a solution about this?

    I re-tested these snippets in my local end and I just made a slight change in BP_Core_Mine_Recently_Active_Widget due to a duplication error. Can you please test again?

    Regards,
    Dimitris

  • Ioannis

    Hello again Dimitris,

    1) The widget that You changed works perfectly!! Could You please tell me what change You made so I can fix and the "Who's Online" widget?

    2) The users in my website will be changing roles. So a user may go from level 1 or level 2 to just subscriber for a period. What I am trying to achieve is that if a client (logged out user) has bookmarked an ex-level 1 member's profile who has become now subscriber or visits the subscriber's profile through a link (from the authors page) then been directed to another page. For example if sb types: mydomain.xx/members/John and if John has become subscriber, then visitor to be redirected. So I need the code to work for all the subscribers profile pages but not for the other roles.

    I know that I have tired You and Thank You so so much for your Patience and support!!!
    Ioannis

  • Dimitris

    Hey Ioannis,

    1) The widget that You changed works perfectly!! Could You please tell me what change You made so I can fix and the "Who's Online" widget?

    Each widget class had a little function to check user roles. As I had the same name on both of these classes, the second time PHP were throwing an error for duplicate functions.
    The first class shouldn't change, there's no need to (double checked!).
    Just make sure that you're using this widget inside a sidebar. :wink:

    2) The users in my website will be changing roles. So a user may go from level 1 or level 2 to just subscriber for a period. What I am trying to achieve is that if a client (logged out user) has bookmarked an ex-level 1 member's profile who has become now subscriber or visits the subscriber's profile through a link (from the authors page) then been directed to another page. For example if sb types: mydomain.xx/members/John and if John has become subscriber, then visitor to be redirected. So I need the code to work for all the subscribers profile pages but not for the other roles.

    Try this snippet instead to see how it responds to your needs.
    First it checks if the user is logged-in, then if the displayed member is a subscriber.

    function redirect_members() {
      // redirect non logged-in members
      if ( !is_user_logged_in() ) {
        // get the ID of displayed member
        $displayed_user = bp_displayed_user_id();
        if (in_array($displayed_user,get_subscribers())) {
          wp_redirect(site_url('/your-new-page-slug'));
          exit();
        }
      }
    }
    add_action( 'wp', 'redirect_members', 1 );
    
    // get all subscribers
    function get_subscribers() {
      $blogusers = get_users( 'role=subscriber' );
      // Array of WP_User objects.
      $exclude = array();
      foreach ( $blogusers as $user ) {
        $exclude[] .= esc_html( $user->ID );
      }
      return $exclude;
    }

    Have a good one,
    Dimitris :slight_smile:

  • Ioannis

    Hey Dimitris,

    The last code was exactly what I needed and thank you very much about that!!!!! Something very strange happens with "Who's online" widget. If I use it in my sidebar all the widgets dissapear from the sidebar only in Members page and the Group pages. So I changed line 77 of "BP_Core_Mine_Whos_Online_Widget"

    function pc_get_userrole ($user_id) {
    to
    function da_get_userrole ($user_id) {
    After I changed the code everything worked properly in Members page and Group Pages but the widgets dissapeared again from the sidebar in every other page of website. So I can make it only work for Groups and Member Page either for the other pages of my site. Do You think that there is an easy solution for that?

    Thank You,
    Ioannis

  • Dimitris

    Hey there Ioannis,

    The last code was exactly what I needed and thank you very much about that!!!!!

    I'm really glad that we made this work for you! :slight_smile:

    So I changed line 77 of "BP_Core_Mine_Whos_Online_Widget"
    function pc_get_userrole ($user_id) {
    to
    function da_get_userrole ($user_id) {

    As I just saw you correctly inverted this. As you may have seen, this function in line#77 is being used in line#90.
    The same thing goes with the BP_Core_Mine_Recently_Active_Widget, the same function is in place (with different name to surpass duplication of functions in case both widgets are used in a page) in line#88 and it's being used in line#101.

    So I can make it only work for Groups and Member Page either for the other pages of my site. Do You think that there is an easy solution for that?

    I just confirmed in my local end that both of these widgets are being displayed correctly in non-BuddyPress pages, like homepage and single posts. Having said that, can you please point the problematic pages on your site and the sidebar location in which you're using thee new widgets?

    Please advise,
    Dimitris :slight_smile:

    PS. In case you feel confident, and as the website is still under construction, feel free to enable WP_DEBUG and see if any error occurs whenever you're dealing with inconsistencies. :wink:

  • Ioannis

    Dimitris,

    I have no words....I adore You man!!! I changed the class name in line 90 too and everything works excellent in my website now!!! I believe the issue was because I had previously added the same filter in Members and in Group directories. Congratulations for being so so so Professional!!!! You have made so difficult things for me so easy and You found a solution in whatever I need!!! Thank You a lot and wish You the Best man!!!

    Warm Regards,
    Ioannis

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.