How to import and export all WordPress users using WP CLI
Like everything with WordPress, there’s usually a plugin to help, but we don’t need one to import users as WP CLI can do this.
Here’s the simple process, starting with exporting the user from an existing WP database. We’ll refer to the source database as source-db and the target database as target-db and I’ll assume you have access to both WordPress instances via WP CLI.
Step 1. Export WordPress users
This step will be working with the source-db.
- note the asterisk in the table name – use this to save typing the exact table name for your specific WordPress database
- note the name of the exported file, users.sql – this makes it clear to identify the contents of this file
$ wp db export --tables=$(wp db tables 'wp_*_users') users.sql
Step 2. Export WordPress usermeta
This step will be wokring with the source-db.
- as above, note the wildcard and filename
$ wp db export --tables=$(wp db tables 'wp_*_usermeta') usermeta.sql
Step 3. Optional backup of users and usermeta
This step will be working with the target-db. It’s an optional backup of the users and usermeta tables before importing the new data.
- repeat step 1 (but working with the target-db)
- name the file backup-users.sql
- repeat step 2 (but working with the target-db)
- name the file backup-usermeta.sql
Step 4. Move the exported files to an accessible location for importing
If you have GUI access to both file systems, then you can simply copy/download users.sql and usermeta.sql from the source instance and paste them into the target instance. I used rsync (but scp will work) to copy from a remote server to a local development server. I was working in the target instance of WordPress via the commandline:
users.sql: $ rsync -azP user@source:path/to/file/users.sql .
usermeta.sql: $ rsync azP user@source:path/to/file/usermeta.sql .
- note the
.
at the end, this just means the destination path is the current directory. You can state the relative path if needed
Step 5. Import WordPress users
This step will be working with the target-db.
$ wp db import users.sql
Step 6. Import WordPress usermeta
This step will be working with the target-db.
$ wp db import usermeta.sql
Step 7. Optional cleanup
This is an optional step to delete exported, but it’s one I’d strongly recommend doing it, especially if you’ve got the users.sql and usermeta.sql files sitting in a public folder.
- repeat this step for each WordPress instance
$ rm users.sql usermeta.sql
$ rm backup-users.sql backup-usermeta.sql
Conclusion
Using WP CLI makes this a very easy process that only take a couple of minutes. On top of that it saves using yet another plugin to carry out a simple task. If you’d like help with this or any other WordPress related challenge, please get in touch.