Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
BuddyPress same gender users visibility
<?php
/**
* Filters Users based on Gender. Make sure only users of same genders are visible.
*/
class BuddyDev_Same_Gender_Based_Member_Filter {
/**
* Boot
*
* @return BuddyDev_Same_Gender_Based_Member_Filter
*/
public static function boot() {
$self = new self();
$self->setup();
return $self;
}
/**
* Setup hooks.
*/
private function setup() {
add_filter( 'bp_after_has_members_parse_args', array( $this, 'filter_args' ) );
add_action( 'bp_template_redirect', array( $this, 'check_access' ), 10, 2 );
}
/**
* Modifies members loop args to filter out users of opposite gender.
*
* @param array $args Array of group allowed parameters.
*
* @return array
*/
public function filter_args( $args ) {
// do not filter if user is not logged in, or is super admin or we are inside dashboard.
if ( ! is_user_logged_in() || is_super_admin() || ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) {
return $args;
}
$gender = $this->get_gender( bp_loggedin_user_id() );
if ( $gender ) {
$args['member_type'] = $gender;
}
return $args;
}
/**
* Restricts access to user profile.
*
* Only allows profile owner, user of opposite gender or site admins to view.
*/
public function check_access() {
if ( ! is_user_logged_in() || ! bp_is_user() || bp_is_my_profile() || is_super_admin() ) {
return;
}
$gender = $this->get_gender( bp_loggedin_user_id() );
if ( ! $gender ) {
return;
}
// do not allow access for opposite gender.
if ( ! bp_has_member_type( bp_displayed_user_id(), $gender ) ) {
bp_core_add_message( __( 'Access denied.' ), 'error' );
bp_core_redirect( bp_loggedin_user_domain() );
}
}
/**
* Finds the gender for the given user.
*
* @param int $user_id user id.
*
* @return string|null
*/
private function get_gender($user_id ) {
$gender = null;
$member_types = bp_get_member_type( $user_id, false );
if ( empty( $member_types ) ) {
$gender = null;
} elseif ( $this->is_user_male( $user_id ) ) {
$gender = 'male';
} elseif ( $this->is_user_female( $user_id ) ) {
$gender = 'female';
}
return $gender;
}
/***
* Checks if user is male or not.
*
* @param int $user_id User id to check.
*
* @return bool
*/
private function is_user_male( $user_id ) {
return bp_has_member_type( $user_id, 'male' );
}
/***
* Checks if user is female or not.
*
* @param int $user_id User id to check.
*
* @return bool
*/
private function is_user_female( $user_id ) {
return bp_has_member_type( $user_id, 'female' );
}
}
BuddyDev_Same_Gender_Based_Member_Filter::boot();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment