Create contributeur with CSV file

Home » Snippets » Create contributeur with CSV file

Created with:




Customize with WPTurbo AI

Add Snippet To Project

New Project
Add To Existing Project
 * Create WordPress Users from CSV with the Contributor Role
function arcensoft_create_users_from_csv() {
    // Path to the CSV file
    $csv_file = '/path/to/users.csv';
    // Check if the file exists
    if ( ! file_exists( $csv_file ) ) {
        return new WP_Error( 'file_not_found', 'CSV file not found.' );
    // Get the CSV data
    $csv_data = array_map( 'str_getcsv', file( $csv_file ) );
    // Remove the header row
    $header = array_shift( $csv_data );
    // Loop through each row and create a user
    foreach ( $csv_data as $row ) {
        $username = $row[0]; // Username is the first column in the CSV
        $email = $row[1]; // Email is the second column in the CSV
        $password = $row[2]; // Password is the third column in the CSV
        // Check if the username already exists
        if ( username_exists( $username ) ) {
            continue; // Skip this row and move to the next one
        // Create the user with the 'contributor' role
        $user_id = wp_insert_user( array(
            'user_login' => $username,
            'user_email' => $email,
            'user_pass'  => $password,
            'role'       => 'contributor', // Set the user role to 'contributor'
        ) );
        // Check if user creation was successful
        if ( is_wp_error( $user_id ) ) {
            continue; // Skip this row and move to the next one
        // Set any additional user meta data if needed
        // Example: update_user_meta( $user_id, 'first_name', $row[3] );
        // Example: update_user_meta( $user_id, 'last_name', $row[4] );
    return 'Users created successfully.';

// Call the function to create users from CSV with the 'contributor' role


In this updated code, the only change is in the wp_insert_user() function call. We added the 'role' => 'contributor' parameter to set the user role as a contributor. This ensures that all users created from the CSV file will have the contributor role.

By default, wp_insert_user() assigns the role of "Subscriber" if no role is specified. However, by explicitly setting the 'role' parameter to 'contributor', we assign the contributor role to the created users.

Remember to update the $csv_file variable with the correct path to your CSV file. After that, execute the code by calling the arcensoft_create_users_from_csv() function. The function will read the CSV file, create WordPress users with the contributor role, and set any necessary user meta data if required.

Register an account to save your snippets or go Pro to get more features.