Monthly Archives: March 2024

Dynamic Dropdown Search Fields

The following code turns a standard BP Profile Search field into a dynamic dropdown search field. Dynamic means that the dropdown list contains only the values that users have actually selected in their profiles.

Let’s say your user profile contains a Country dropdown field with dozens of countries, but your users are only from a handful of them. When you add this code to your bp-custom.php file, the Country search field in your BP Profile Search form will only list the countries where at least one user can be found.

add_action ('bps_field_before_search_form', 'bps_dynamic_dropdown');
function bps_dynamic_dropdown ($f)
	global $wpdb;

	$ids = array (2, 5);  // IDs of the search fields that will become "dynamic dropdown" search fields
	if (empty ($f->id) || !in_array ($f->id, $ids))  return;

	$query = "SELECT DISTINCT value FROM {$wpdb->prefix}bp_xprofile_data WHERE field_id = {$f->id} ORDER BY value";
	$values = $wpdb->get_col ($query);
	$f->options = array ('' => '');
	foreach ($values as $value)
		$value = stripslashes ($value);
		if ($value == '')  continue;

		$f->options[$value] = $value;

	$f->display = (count ($f->options) == 1)? 'none': 'selectbox';

Please note that the above code does not work for Check Box and Multi-Select Box profile field types, because their values are stored in serialized form.