BuddyPress: Query Users by xProfile Data

Today I had a needed to query BuddyPress users by their extended profile data. I couldn’t find any functions in BuddyPress core that facilitate this, so I wrote my own. Here it is for anyone else who is looking for it:

/**
 * Get users by BuddyPress xprofile data.
 *
 * @param int    $field_id The ID of the field to search in.
 * @param string $value    The value to search for.
 * 
 * @return int[] The IDs of the users matching the search.
 */
function my_bp_get_users_by_xprofile( $field_id, $value ) {

	global $wpdb;

    $user_ids = $wpdb->get_col(
    	$wpdb->prepare(
    		"
    			SELECT `user_id`
    			FROM `{$wpdb->prefix}bp_xprofile_data`
    			WHERE `field_id` = %d
    				AND `value` = %s
    		"
    		, $field_id
    		, $value
    	)
    );
}

Usage:

$user_ids = my_bp_get_users_by_xprofile( 5, 'find me' );

If you need to get the field ID, you can use xprofile_get_field_id_from_name( 'field name' ).

Enjoy!

1 thought on “BuddyPress: Query Users by xProfile Data

  1. http://Listcleanupt.com

    We are a group of volunteers and starting a new scheme in our community.

    Your site offered us with valuable info to work on. You have done a formidable job and our entire community will be thankful to you.

    Reply

Leave a Reply to http://Listcleanupt.com Cancel reply

Your email address will not be published. Required fields are marked *