Export database table to csv in wordpress

Export database table to csv in wordpress

In this article i am explaining how to export database table data into CSV file in WordPress using by admin menu.

If your are looking for downloading data from table using WordPress admin panel by clicking on a button than this code for you. I did this code for download user data from the wp_users table then i am edit and representing here.

What we are cover in this tutorial

  1. How to create custom menu in WordPress admin
  2. Create file downloading link
  3. Fetch data from table and download

How to create custom menu in WordPress admin

Below is the code for creating custom menu in WordPress admin panel copy and past code into function.php file of your theme.

/*Add Custome menu for coupon code*/
function create_custome_menu_admin(){
	$page_title = 'Page Title';
	$page_name = 'Menu Name';
	$page_scope = 'manage_options';
	$page_url = 'page-url';
	$page_func = 'call_back_function_name';
	add_menu_page($page_title, $page_name, $page_scope, $page_url, $page_func);
add_action('admin_menu', 'create_custome_menu_admin');
function call_back_function_name(){

2. Create file downloading link

Again here i am defining call back function, inside call back function i am including a file in that file copy past below code.

function call_back_function_name(){
// code for "include_your_file_name.php"
<h2><a href="website_url/wp-admin/admin.php?page=page-url&action=download_csv_file">Download Users</a></h2>

3. Fetch data from table and download

In this step we will create how to download data from perticular database table copy and past belo code inside your include file. Here my include file name is “include_your_file_name.php”.

if ( isset($_GET['action'] ) && $_GET['action'] == 'download_csv_file' )
	// Query
	$statement = $wpdb->get_results("SELECT * FROM `table_name` ORDER BY `id` DESC");
	// file creation
	$wp_filename = "filename_".date("d-m-y").".csv";
	// Clean object
	ob_end_clean ();
	// Open file
	$wp_file = fopen($wp_filename,"w");
	// loop for insert data into CSV file
	foreach ($statement as $statementFet)
		$wp_array = array(
	// Close file
	// download csv file
	header("Content-Description: File Transfer");
	header("Content-Disposition: attachment; filename=".$wp_filename);
	header("Content-Type: application/csv;");
About Author

My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.