Last active
April 22, 2024 15:25
-
-
Save spacedmonkey/9688152 to your computer and use it in GitHub Desktop.
Export to CSV - WP CLI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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,[email protected],Bob Jones,contributor | |
* newuser1,[email protected],New User,author | |
* existinguser,[email protected],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