|
| 1 | +#!/bin/env bash |
| 2 | + |
| 3 | +# Creates users from a CSV. On multisite, adds user to every site. |
| 4 | +# |
| 5 | +# CSV expects to have the following values with no header row as labels: |
| 6 | +# username |
| 7 | +# email |
| 8 | +# role (a valid WP role) |
| 9 | +# superadmin (1 or 0) |
| 10 | + |
| 11 | +source 'source/includes.sh'; |
| 12 | + |
| 13 | +# Check if this is a multisite/network installation of WordPress. |
| 14 | +is_multisite=$(wp_skip_all config get MULTISITE); |
| 15 | + |
| 16 | +echo; |
| 17 | + |
| 18 | +if [ "$is_multisite" == 1 ]; then |
| 19 | + echo 'Multisite detected'; |
| 20 | + echo ' Users will be added to every network site'; |
| 21 | +else |
| 22 | + echo 'Multisite NOT detected'; |
| 23 | +fi |
| 24 | + |
| 25 | +echo; |
| 26 | + |
| 27 | +# Prompt the user for the path to a CSV with username and email. |
| 28 | +read -r -p 'Path to CSV file with users [./user-create.csv]: ' csv_path; |
| 29 | + |
| 30 | +# Set default value if empty string provided. |
| 31 | +[[ -z "$csv_path" ]] && csv_path='./user-create.csv'; |
| 32 | + |
| 33 | +# Ensure the file actually exists. |
| 34 | +if [[ ! -f "$csv_path" ]]; then |
| 35 | + |
| 36 | + echo "The file you provided does not exist: ${csv_path}"; |
| 37 | + exit 1; |
| 38 | + |
| 39 | +fi |
| 40 | + |
| 41 | +###################################################### |
| 42 | +# Read the CSV and create the user(s) |
| 43 | +###################################################### |
| 44 | + |
| 45 | +# Init the user counter. |
| 46 | +user_count=0; |
| 47 | + |
| 48 | +# Loop over the entire CSV file. |
| 49 | +while IFS="," read -r username email role superadmin; do |
| 50 | + |
| 51 | + # Create the user. Only output WPCLI success message on successful creation. |
| 52 | + if new_user_id=$(wp_skip_all user create --porcelain "$username" "$email" --role="$role" >&1 ); then |
| 53 | + |
| 54 | + # Update the count for each successful user creation. |
| 55 | + ((user_count++)); |
| 56 | + |
| 57 | + echo "'$username' was successfully created."; |
| 58 | + |
| 59 | + # Check if the user should be a superadmin. |
| 60 | + if [[ "1" == "$superadmin" ]]; then |
| 61 | + |
| 62 | + wp_skip_all super-admin add $username; |
| 63 | + |
| 64 | + else |
| 65 | + |
| 66 | + for site_url in $(wp_skip_all site list --field="url" --archived=0 --deleted=0 --spam=0); do |
| 67 | + |
| 68 | + # The user is not a superadmin so add them to each site individually. |
| 69 | + wp_on_site user set-role "$new_user_id" "$role"; |
| 70 | + |
| 71 | + done; |
| 72 | + |
| 73 | + fi |
| 74 | + |
| 75 | + else |
| 76 | + |
| 77 | + # Output any errors from WPCLI. |
| 78 | + >&2 |
| 79 | + |
| 80 | + fi |
| 81 | + |
| 82 | +done < "$csv_path" |
| 83 | + |
| 84 | +echo "Users added: ${user_count}"; |
0 commit comments