Skip to content

Instantly share code, notes, and snippets.

@kidino
Created March 30, 2025 03:11
Show Gist options
  • Save kidino/26dd6b29534f41e278dc1e51246111df to your computer and use it in GitHub Desktop.
Save kidino/26dd6b29534f41e278dc1e51246111df to your computer and use it in GitHub Desktop.
CLI tool to bulk add users through CSV file into WordPress with a role
<?php
// Ensure the script is run from CLI
if (php_sapi_name() !== 'cli') {
die("This script can only be run from the command line.\n");
}
// Check for required CLI arguments
if ($argc < 3) {
die("Usage: php import_users.php <csv_file> <role>\n");
}
$csvFile = $argv[1];
$role = $argv[2];
// Load WordPress environment
require_once dirname(__FILE__) . '/wp-load.php';
if (!file_exists($csvFile)) {
die("CSV file not found: $csvFile\n");
}
// Open the CSV file
$handle = fopen($csvFile, 'r');
if (!$handle) {
die("Error opening CSV file.\n");
}
// Read header row
$headers = fgetcsv($handle);
while (($data = fgetcsv($handle)) !== false) {
$userData = array_combine($headers, $data);
// Extract email from the correct column
$email = sanitize_email($userData['Email']);
if (!is_email($email)) {
echo "Invalid email: {$userData['Email']}\n";
continue;
}
// Extract name and split into first & last name
$nameParts = explode(' ', sanitize_text_field($userData['Name']), 2);
$first_name = $nameParts[0] ?? '';
$last_name = $nameParts[1] ?? '';
$user_id = email_exists($email);
if ($user_id) {
echo "User already exists: $email - Adding role if not assigned\n";
} else {
// Generate a random password
$password = wp_generate_password();
// Create user
$user_id = wp_create_user($email, $password, $email);
if (is_wp_error($user_id)) {
echo "Error creating user: $email\n";
continue;
}
// Update user meta (optional)
wp_update_user([
'ID' => $user_id,
'first_name' => $first_name,
'last_name' => $last_name
]);
echo "User added: $email\n";
}
// Assign role without overriding existing roles
$user = new WP_User($user_id);
if (!$user->has_role($role)) {
$user->add_role($role);
echo "Role '$role' added to user: $email\n";
} else {
echo "User $email already has role '$role'.\n";
}
}
// Close the file
fclose($handle);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment