Skip to content

Commit 517a1c4

Browse files
Merge pull request #5 from JasonRaveling/user-create
User rename script
2 parents ed1b74f + 2d941a7 commit 517a1c4

2 files changed

Lines changed: 66 additions & 1 deletion

File tree

user-create.sh

100644100755
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ while IFS="," read -r username email role superadmin; do
7474

7575
else
7676

77-
# Output any errors from WPCLI.
77+
# Output any errors from WPCLI for the user creation.
7878
>&2
7979

8080
fi

user-rename.sh

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#!/bin/env bash
2+
3+
# Renames user(s) to any given string.
4+
#
5+
# Use caution! The new name can be a non-standard WP username, with any characters.
6+
7+
source 'source/includes.sh';
8+
9+
# Prompt the user for the path to a CSV with username and email.
10+
read -r -p 'Path to CSV file with users [./user-rename.csv]: ' csv_path;
11+
12+
# Set default value if empty string provided.
13+
[[ -z "$csv_path" ]] && csv_path='./user-rename.csv';
14+
15+
# Ensure the file actually exists.
16+
if [[ ! -f "$csv_path" ]]; then
17+
18+
echo "The file you provided does not exist: ${csv_path}";
19+
exit 1;
20+
21+
fi
22+
23+
######################################################
24+
# Read the CSV and update the user(s)
25+
######################################################
26+
27+
# Init the user counter.
28+
user_count=0;
29+
30+
# Loop over the entire CSV file.
31+
while IFS="," read -r old_username new_username; do
32+
33+
echo "Changing username: ${old_username}";
34+
35+
# Ensure the user exists by getting the user ID.
36+
if user_id=$(wp_skip_all user get "${old_username}" --field=ID >&1 ); then
37+
38+
# Set the SQL query for updating the current user's username and nicename.
39+
user_update_query="UPDATE wp_users SET user_login = '${new_username}', user_nicename = '${new_username}' WHERE ID = '${user_id}'";
40+
41+
# Update the username and check the status of the change.
42+
if $(wp_skip_all db query "$user_update_query" >&1 ); then
43+
44+
# Update the count for each successful user creation.
45+
((user_count++));
46+
47+
echo "Changed to: ${new_username}";
48+
49+
else
50+
51+
# Output any errors from WPCLI from the query.
52+
>&2
53+
54+
fi
55+
56+
else
57+
58+
# Output any WPCLI error related to checking if the user exists.
59+
>&2;
60+
61+
fi
62+
63+
done < "$csv_path"
64+
65+
echo "Users updated: ${user_count}";

0 commit comments

Comments
 (0)