Importing custom user fields

Our  CSV User Importer add-on imports up to 10 supported fields, though custom fields can also be imported with a small amount of custom code.

Add the fields to your CSV file

First you'll need to add the custom fields to your CSV file. Each custom field should have a column heading (this name is important - we'll be using it later!) and the value should be entered for each user. For example, I might create a new column called "birthday" and my CSV file might look like this:

You can see the custom birthday field highlighted in yellow.

Importing the data

You'll need to setup a place to put the custom code. This can be in your child theme or a custom plugin file. If you need help doing this you can read  our documentation article on adding code snippets.

Here's the code we'll be adding:

/**
 * Import custom user fields
 * 
 * @param int    $user_id         ID number of the user being imported.
 * @param array  $user_data       Array of user data, including first name, last name, and email.
 * @param int    $subscription_id ID number of the subscription this user is being added to.
 * @param string $status          Status this user is being set to.
 * @param string $expiration      User's new expiration date in MySQL format.
 * @param array  $row             Array of all data in this user's row.
 */
function ag_rcp_import_custom_fields( $user_id, $user_data, $subscription_id, $status, $expiration, $row ) {

    $birthday = $row['birthday']; // Replace 'birthday' with your column heading name.

    if ( ! empty( $birthday ) ) {
        // Change 'birthday' to the user meta key you'd like to save the data as.
        update_user_meta( $user_id, 'birthday', sanitize_text_field( $birthday ) );
    }

}

add_action( 'rcp_user_import_user_added', 'ag_rcp_import_custom_fields', 10, 6 );

There are a few things you'll need to edit to make this code your own:

  • Change the variable name $birthday to something that reflects your custom field. (This ultimately doesn't matter, it's just for keeping your code neatly labelled!) Update all three instances of this throughout the code.
  • In $row['birthday'] replace birthday with the name of your column heading.
  • In the update_user_meta function, replace 'birthday' with the user meta key you'd like to use when saving the data. (Use underscores instead of spaces.)

Once you've added your code, you can then proceed to import your CSV file. During the import, all custom fields will be added to the account's user meta. You can then display this data in the admin area (with the  rcp_edit_member_after action) and/or front-facing pages (with the rcp_profile_editor_after action).