Skip to content

Instantly share code, notes, and snippets.

@spacedmonkey
Last active April 22, 2024 15:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spacedmonkey/9688152 to your computer and use it in GitHub Desktop.
Save spacedmonkey/9688152 to your computer and use it in GitHub Desktop.
Export to CSV - WP CLI
/**
* Export users to a CSV file.
*
* ## OPTIONS
*
* <file>
* : The CSV file to export users to.
*
* ## EXAMPLES
*
* wp user-ipc export-csv /path/to/users.csv
*
* Sample users.csv file output:
*
* user_login,user_email,display_name,role
* bobjones,bobjones@domain.com,Bob Jones,contributor
* newuser1,newuser1@domain.com,New User,author
* existinguser,existinguser@domain.com,Existing User,administrator
* @synopsis <file> [--role=<role>] [--number=<number>]
*
* @subcommand export-csv
*/
public function export_csv( $args, $assoc_args ) {
$defaults = array(
'role' => '',
'number' => ''
);
$assoc_args = wp_parse_args( $assoc_args, $defaults );
$blog_users = get_users($assoc_args);
$filename = $args[0];
if ( file_exists( $filename ) ) {
WP_CLI::warning( sprintf( "File alredy exists. The following file will be overwritten %s", $filename ) );
}
$results = array();
$results[] = array('user_login','user_email','display_name','role');
foreach ($blog_users as $user) {
$results[] = array($user->user_login, $user->user_email, $user->display_name, $user->roles[0]);
}
$fp = fopen($filename, 'w+');
foreach ($results as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
WP_CLI::success( sprintf( "File created: %s", $filename ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment