BuddyDev

Show only users of opposite genders on BuddyPress site

If you are creating a dating site or something that needs you to filter users list based on current user's gender, It may not be vary obvious in BuddyPress. Believe me , It is easier than what you might think.

Basic Premise:-

BuddyPress does not have a way to specify user gender's. We can either use Profile field(dropdown/radio) or member type. I will use member type for the genders. The benefit of using member type is, it allows efficient filtering of the users.

Assumptions:-

I am assuming you have two member types 'male' and 'female' registered. Any users with male member type will be considered as male and the same goes for the female member type. I am also considering male member type as opposite of the female member type for the sake of our use case.

Goals:-

  • We will filter members listings and only show users of opposite gender if a user is logged in, and has the gender set.
  • When a user of same gender tries to access other user's profile, we deny the access.
  • We do not do anything if a user is not logged in.

Code:-

We will write a few utility functions that will help us with our implementation. Here is the list of functions we plan to use.

  • is_user_male( $user_id ) : bool
  • is_user_female( $user_id ): bool
  • get_user_gender( $user_id ) : string (  'male' or 'female' )
  • get_opposite_gender( $user_id ): string ( 'male' or 'female' )

That's our list of utility functions. I have implemented these as class methods.

Here is the concrete implementation of the whole filtering of BuddyPress users.

Please put this code in your bp-custom.php and you will be good to go.

Resources:-

Comments are closed.