Syncing xProfile Data to User Meta in BuddyPress

This code enables automatic saving of BuddyPress xProfile fields to the usermeta table whenever a user updates their profile. The profile data will be saved as user meta with a specified prefix (e.g., xprofile_). This is useful for integrating BuddyPress profile data into other parts of your WordPress site that may depend on usermeta instead of xProfile fields.

Features

  • Automatically syncs BuddyPress xProfile fields to WordPress user meta on profile updates.
  • Can be customized to work with any xProfile field by simply changing the field names.

Code Implementation

function wbcom_save_xprofile_to_usermeta_on_update($user_id) {
    // Define your xProfile field names here
    $fields_to_sync = array(
        'Gender',    // Replace with your actual xProfile field name
        'Location'   // Replace with your actual xProfile field name
    );

    // Loop through each field and save its value as user meta
    foreach ($fields_to_sync as $field_name) {
        $field_value = xprofile_get_field_data($field_name, $user_id);

        if ( ! empty( $field_value ) ) {
            // Save as user meta with 'xprofile_' prefix
            update_user_meta($user_id, 'xprofile_' . strtolower($field_name), $field_value);
        }
    }
}

// Hook the function to the BuddyPress profile update action
add_action('xprofile_updated_profile', 'wbcom_save_xprofile_to_usermeta_on_update', 10, 1);

How It Works

  1. xProfile Field Names: You define an array containing the names of the xProfile fields you want to sync (e.g., ‘Gender’, ‘Location’).
  2. Profile Update Hook: The function is hooked to the xprofile_updated_profile action, ensuring that every time a user updates their profile, their xProfile data is saved to usermeta.
  3. Saving User Meta: The function loops through the fields and saves each one to usermeta, with a xprofile_ prefix added to the meta key (e.g., xprofile_gender and xprofile_location).

Customization

  • You can easily add more xProfile fields to the $fields_to_sync array.
  • If needed, adjust the prefix xprofile_ in the update_user_meta function to fit your own preference.

Use Case

This approach is useful when integrating BuddyPress xProfile data with plugins or functionalities that depend on usermeta. It helps bridge the gap between BuddyPress profile data and other WordPress components.

Update on September 8, 2024