If anyone wants a filter to fix the case where a given user hasn’t edited their profile yet (and thus doesn’t have the bp_xprofile_visibility_levels user meta), resulting in all of their fields being visible:
// Fix for BuddyPress not respecting the default xProfile field visibility
// if a user has not yet edited their profile (and thus saving the user meta
// <code>bp_xprofile_visibility_levels</code> for that user).
// See: https://buddypress.org/support/topic/only-me-extended-profile-field-visible-to-all-users/
// See: https://buddypress.trac.wordpress.org/ticket/8093
add_filter( 'bp_xprofile_get_hidden_fields_for_user', function ( $hidden_fields, $displayed_user_id, $current_user_id ) {
if ( empty( $hidden_fields ) ) {
// Get the visibilities that should be hidden for the current user pair.
$hidden_field_types_for_user = bp_xprofile_get_hidden_field_types_for_user( $displayed_user_id, $current_user_id );
// Get the visibility defaults for all xProfile fields.
$default_visibility_levels = \BP_XProfile_Group::fetch_default_visibility_levels();
// Create the list of field IDs that should be hidden.
$hidden_fields = array_keys( array_filter(
$default_visibility_levels,
function ( $default_visibility_level ) use ( $hidden_field_types_for_user ) {
return empty( $default_visibility_level['default'] ) || in_array( $default_visibility_level['default'], $hidden_field_types_for_user, true );
}
) );
}
return $hidden_fields;
}, PHP_INT_MAX, 3 );