Excluding Users From BuddyPress Based On User Meta In WordPress
Excluding Users From BuddyPress Based On User Meta In WordPress
I’ve recently taken on a fairly large project that I’m excited to be bringing to life. The project will encompass several different elements, one of them being a BuddyPress integration. I’ve worked with BuddyPress in the past but never with this much customization so I’ve definitely be doing some digging into different built-in functions.
One element I needed to achieve involved excluding specific users from the BuddyPress members list based on a custom user meta field. Which brings us to our first function. The below would go in your active themes functions.php file. Here it is in its entirety:
// Remove users from BuddyPress
add_action('bp_ajax_querystring','bpdev_exclude_users',20,2);
function bpdev_exclude_users($qs=false,$object=false){
$excluded_user = '';
$i=0;
//list of users to exclude
$args = array(
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'meta_name',
'value' => 'meta_value',
'compare' => '='
),
)
);
$user_query = new WP_User_Query( $args );
$businesses = $user_query->get_results();
// Check for results
if (!empty($businesses)) {
foreach ($businesses as $business) { $i++;
$excluded_user = $business->ID . ', ';
}
}
if(!empty($excluded_user)) {
if($object!='members')//hide for members only
return $qs;
$args=wp_parse_args($qs);
//check if we are listing friends?, do not exclude in this case
if(!empty($args['user_id']))
return $qs;
if(!empty($args['exclude']))
$args['exclude']=$args['exclude'].','.$excluded_user;
else
$args['exclude']=$excluded_user;
$qs=build_query($args);
return $qs;
}
}
//Remove from member count
add_filter('bp_get_total_member_count','bpdev_members_correct_count');
function bpdev_members_correct_count($count){
$excluded_user = '';
$i=0;
//list of users to exclude
$args = array(
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'meta_name',
'value' => 'meta_value',
'compare' => '='
),
)
);
$user_query = new WP_User_Query( $args );
$businesses = $user_query->get_results();
// Check for results
if (!empty($businesses)) {
foreach ($businesses as $business) { $i++;
$excluded_user = $business->ID . ', ';
}
}
$excluded_users_count= $i;
return $count-$excluded_users_count;
}
The only aspect of this function you will want to change is both of the user queries (one for removing members, one for updating member count):
'key' => 'meta_name', 'value' => 'meta_value', 'compare' => '='
This will need to be updated with the user meta name and then the value you are looking to match it to. Overall a great function to kick off this BuddyPress work and to exclude a specific group of users.
Enjoy!




Comments:
Share Your Thoughts