Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Export all WordPress user roles to CSV file
<?php
/* Project: User Role Editor WordPress plugin
* Adds admin menu item "Tools->Export roles (CSV)" and allows to export all user roles to CSV file with one click
* Setup: Install as a Must Use plugin: https://codex.wordpress.org/Must_Use_Plugins
* Author: Vladimir Garagulia
* Email: support@role-editor.com
* Site: https://role-editor.com
* License: GPL v.3
*/
class URE_Export_Roles_CSV {
function __construct() {
add_action( 'admin_menu', array( $this, 'menu' ) );
add_action( 'admin_init', array($this, 'act'));
}
// end of __construct();
public function menu() {
add_management_page(
'Export Roles (CSV)',
'Export Roles (CSV)',
'ure_export_roles',
'ure-export-roles-csv',
array( $this, 'show' )
);
}
// end of menu()
private function caps_to_string( $capabilities ) {
if ( empty( $capabilities ) ) {
return '';
}
$caps = array();
foreach( $capabilities as $cap=>$allowed ) {
if ( $allowed ) {
$caps[] = $cap;
}
}
$caps_str = implode( ',', $caps );
return $caps_str;
}
// end of caps_to_string()
private function send_data( $data ) {
$timestamp = date('_Y-m-d_h_i_s', current_time('timestamp'));
$file_name = 'wp_roles'. $timestamp .'.csv';
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browsers
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'. $file_name .'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen($data));
echo $data;
}
// end of send_data()
private function is_applicable() {
global $pagenow;
if ($pagenow!=='tools.php') {
return false;
}
if ( !isset($_GET['page']) || $_GET['page']!=='ure-export-roles-csv' ) {
return false;
}
return true;
}
// end of is_applicable()
public function act() {
if (!$this->is_applicable()) {
return;
}
$wp_roles = wp_roles();
$roles = $wp_roles->roles;
$data = '"role_id";"role_name";"capabilities"' . PHP_EOL;
foreach ($roles as $role_id => $role) {
$caps = $this->caps_to_string($role['capabilities']);
$data .= sprintf('"%s","%s","%s"', $role_id, $role['name'], $caps) . PHP_EOL;
}
$this->send_data($data);
exit;
}
// end of act()
}
// end of URE_Export_Roles_CSV
new URE_Export_Roles_CSV();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment