Skip to:
Content
Pages
Categories
Search
Top
Bottom

Reply To: Saving an array with xprofile_set_field_data

@landwire

Participant

ok, in the end I used this to solve the problem, as I ran into issues when trying to save an array of arrays with the bp functions. Just in case someone is looking for this as well:
First: I stripped the slashes before saving serialized data to the DB with a filter
Second: I had to copy/create a different xprofile_get_field_data() function, as it would not get complex serialized values (array of arrays). Single arrays it works ok, but not nested arrays. Basically I had to remove all those filters that were called during xprofile_get_field_data().
It’s hacky, but I tried many options. This seems to be the one that worked in the end.

/**
 * Fetches profile data for a specific field for the user.
 *
 * When the field value is serialized, this function unserializes and filters
 * each item in the array.
 *
 * @package BuddyPress Core
 * @param mixed $field         The ID of the field, or the $name of the field.
 * @param int $user_id         The ID of the user
 * @param string $multi_format How should array data be returned? 'comma' if you want a
 *                             comma-separated string; 'array' if you want an array
 * @uses BP_XProfile_ProfileData::get_value_byid() Fetches the value based on the params passed.
 * @return mixed The profile field data.
 */
function lw_xprofile_get_field_data( $field, $user_id = 0, $multi_format = 'array' ) {

	if ( empty( $user_id ) ) {
		$user_id = bp_displayed_user_id();
	}

	if ( empty( $user_id ) ) {
		return false;
	}

	if ( is_numeric( $field ) ) {
		$field_id = $field;
	} else {
		$field_id = xprofile_get_field_id_from_name( $field );
	}

	//d($field_id, 'The field ID ><><><><><>><>>>>>>>_+++++++++++++');
	if ( empty( $field_id ) ) {
		return false;
	}

	$values = maybe_unserialize( BP_XProfile_ProfileData::get_value_byid( $field_id, $user_id ) );
	//d($values, 'The values <><><>>><><><><><><><><>><');

	return $values;
}

add_filter( 'xprofile_filtered_data_value_before_save', 'lw_strip_slashes_before_db', 10, 3);

function lw_strip_slashes_before_db($filtered_value, $value, $data_obj ) {
	//d($filtered_value, '$filtered_value');
	//d($value, '$value');
	//d($data_obj, '$data_obj');
	if ( is_serialized($value) ) {
		$filtered_value = stripslashes($filtered_value);
	}
	return $filtered_value;
}
Skip to toolbar