Create a CSV File of WordPress User Information with PHP

One of my clients wanted a list of their clients and the client’s information to download on demand. I added the following php code to their themes functions.php file.

This will pull the information from the WordPress user record and user meta table and create the CSV file. When finished, a link is provided to the csv file that was created so that the file can be downloaded.

You may want to change which fields are downloaded from WordPress. To do this, just change the field names in the fields array to match the fields in the user record and the user meta table which you want to download.

The first function will create a new page and add it to the WordPress admin sidebar menu.

function my_admin_menu() {  // add a menu option to the WordPress Admin sidebar
	add_menu_page('CSV', 'CSV File', 'manage_options', 'csv-file', 'csvFile', 'dashicons-admin-post',6);
}

function csvFile() {

    $user_id = $_GET['id'];  // or however you need to get the user id's
    $path = wp_upload_dir();   // or where ever you want the file to go
    $outstream = fopen($path['path']."/shippinglabels.csv", "w");  // the file name you choose

    $fields = array(first_name, last_name, user_email, user_url, description);  // the user information you want in the csv file

    fputcsv($outstream, $fields);  //creates the first line in the csv file
    
    $user = get_user_by('id',$user_id);  // find the user
    $values=array();    // initialize the array
    foreach($fields as $field)
    {
	   $values[$field] =  ($user->$field)  ? $user->$field : get_user_meta($user_id, $field, true);   // check the user record first, if not there, check user meta
    }
    fputcsv($outstream, $values);  //output the user info line to the csv file

    fclose($outstream); 
    echo '<a href="'.$path['url'].'/shippinglabels.csv">Download</a>';  //make a link to the file so the user can download.
}

1 thought on “Create a CSV File of WordPress User Information with PHP”

  1. Hi,

    Can you please guide me how can i use this code? i have already put this in functions.php but didnt see any option in sidebar.

    Also how can i create CSV file for custom post type posts?

    Thanks in Advance.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top