Created
November 26, 2012 17:36
-
-
Save rachelbaker/4149560 to your computer and use it in GitHub Desktop.
WordPress CSV importer upload form
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
<h3><?php echo __('Upload CSV'); ?></h3> | |
<form action="" method="post" enctype="multipart/form-data"> | |
<tr> | |
<td width="20%"><?php echo __('Select file'); ?></td> | |
<td width="80%"><input type="file" name="file" id="file"/></td> | |
</tr> | |
<tr> | |
<td>Submit</td> | |
<td><input type="submit" name="submit"/></td> | |
</tr> | |
</form> | |
<?php | |
if ($_FILES) { | |
// Get the type of the uploaded file. This is returned as "type/extension" | |
$arr_file_type = wp_check_filetype($_FILES['file']['tmp_name']); | |
$uploaded_file_type = $arr_file_type['type']; | |
// Set an array containing a list of acceptable formats | |
$csv_file_types = array('text/csv', 'text/plain', 'application/csv'); | |
if (!function_exists('wp_handle_upload')) { | |
require_once(ABSPATH . 'wp-admin/includes/file.php'); | |
} | |
$uploadedfile = $_FILES['file']; | |
if ($_FILES['file']['type'] !== 'text/csv'){ | |
echo '<pre>ERROR, Only upload files in the CSV format!</pre>'; | |
} | |
else { | |
$upload_overrides = array('test_form' => false); | |
$movefile = wp_handle_upload($uploadedfile, $upload_overrides); | |
echo '<pre>'; | |
if ($movefile) { | |
echo "File is valid, and was successfully uploaded.\n"; | |
var_dump($movefile); | |
} else { | |
echo "ERROR, file was NOT uploaded!\n"; | |
} | |
if (!file_exists($movefile['file']) || !is_readable($movefile['file'])) { | |
return false; | |
} | |
$header = null; | |
$data = array(); | |
# Open the File. | |
if (($handle = fopen($movefile['file'], "r")) !== false) { | |
while (($row = fgetcsv($handle, 1000, ",")) !== false) { | |
if (!$header) { | |
$header = $row; | |
} else { | |
$data[] = array_combine($header, $row); | |
} | |
} | |
fclose($handle); | |
} | |
$new_post_ids = $this->add_posts_from_csv_data($data); | |
echo '</pre>'; | |
} | |
} //end else of file type check |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works well. However, I have a couple of suggestions:
Add
application/vnd.ms-excel
to$csv_file_types = array('text/csv', 'text/plain', 'application/csv');
$csv_file_types = array('text/csv', 'text/plain', 'application/csv', 'application/vnd.ms-excel');
Change
if ($_FILES['file']['type'] !== 'text/csv')
toif (!in_array($_FILES['file']['type'],$csv_file_types))
so that it reads all file types in the$csv_file_types array
.