1

I have about 600 user records I've imported from a WooCommerce site, but they have the email as their username and I need their username to be first.last

So I'm trying to find a SQL way to update all user_login, user_nicename, and display_name fields in the wp_users table with the first_name and last_name information in the wp_usermeta table.

  • user_login should be in the format: first.last
  • user_nicename should be in the format: first-last
  • display_name should be in the format: First Last

This should also only apply to users with the role of "Customer" ( meta_key= wp_capabilities meta_value= a:1:{s:8:"customer";b:1;} in the wp_usermeta table).

I understand basic sql, but not when working with multiple tables. :(

2

You don't need SQL, and shouldn't use it when Core functions will do the job. Part of the reason why is the complexity of the tables (and the fact they might change).

  1. Query your users,
  2. loop through pulling metadata,
  3. and update

Proof of concept:

$u = new WP_User_Query( 
  array( 
    'role' => 'customer' 
  ) 
);
foreach ($u->results as $user) {
  $fn = get_user_meta($user->ID,'first_name',true);
  $ln = get_user_meta($user->ID,'last_name',true);
  $user->data->user_login = strtolower("$fn,$ln");
  $user->data->user_nicename = strtolower("$fn-$ln");
  $user->data->display_name = "$fn $ln";
  wp_update_user($user);
}

You really should create some logic to check that $fn and $ln are not empty and compensate if one or both are.

600 users should update very quickly

1
  • 2
    Thank you. I eventually came to the same conclusion. I think the final piece is you have to update user_login directly because wp_update_user() won't do it. $wpdb->update($wpdb->users, array('user_login' => $username), array('ID' => $user->ID)); – wired Jan 9 '16 at 5:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.