BuddyPress: How to get info of users filtered by some x-profile data? [closed]

You will want to use the $wpdb class to execute a query for users with a certain x-profile field value.

I’m no MySQL expert, so someone else likely has a better way to write this query (if you do, please share it and I’ll update my code), but here’s one approach to it.

This approach assumes you know the ID of the the BuddyPress profile field you are wanting to run the report on, if you don’t, you can alter the query to check the [prefix]_bp_xprofile_fields table for a specific field and use it’s ID for the rest of the query.

This approach also assumes you are looking for the email address associated with the users’ WordPress accounts and not some other email field you’ve defined in BuddyPress, if you are looking for one in BuddyPress, you’ll need to perform a somewhat more complicated query because the [prefix]_bp_xprofile_data table will have the value you want to check against and the value you want to return under the value field in the table.

//create a simple function that will retrieve your desired results
function wpse97684_get_desired_users($field_id, $field_val) {
    //$field_id: (int) this is the ID of the field you'd like to check against
    //$field_val: (str) this is the value you want those users to have in the field

    global $wpdb;
    $bp_table = $wpdb->prefix . 'bp_xprofile_data'; 

    $query = $wpdb->prepare(
        "SELECT U.user_email " .
        "FROM $bp_table B, $wpdb->users U " .
        "WHERE B.user_id = U.ID " .
        "AND B.field_id = %d " .
        "AND B.value = %s"
       , $field_id
       , $field_val
    );

    $get_desired = $wpdb->get_results($query);

    if(count($get_desired)) {
        return $get_desired;
    } else {
        return false;
    }
}

//to call this function, just pass the desired field ID and the desired value
wpse97684_get_desired_users(4, 'Yes'); //example

Now, I’m not certain how you’ll be using this data or where you’ll be implementing it, so I left it in the raw object format that the $wpdb class returns.

You’d probably want to put this into a plug-in and format the returned value into a CSV or something if you plan to feed it into an email campaign system (you’d also probably want to check the usermeta table for the first and last name fields because most of the email systems I’ve worked with require those, too).

But, this should get you going in the right direction.