I’m trying to make a plugin that as part of its task uploads csv files to the wordpress install. Deciding to integrate as closely as possible using wordpress functions wherever possible I am saving the uploaded file to the correct current wordpress folder (with the help of the wp_upload_dir() function).
I am then adding the upload into the posts table as an attachment so that users can manage it via the media page. This is being done with the build in function wp_insert_attachment(). This is where things seem to go wrong.
Basically the file names I parse to the function have spaces in them but when I look at the GUID values in the posts table the spaces have been taken out. If I add the same file via the wordpress media page interface the spaces are replaced with hyphens. I understand why wordpress adds hyphens to make the file url safer in old browsers that couldn’t handle spaces well, however why is the space being removed when I parse to wp_insert_attachment?
So to confirm; uploading “Work Spreadsheet.csv” via the wordpress interface results in an expected GUID of
http://domain.com/wordpress/wp-content/uploads/2013/11/Work-Spreadsheet.csv
However via my plugin code
http://domain.com/wordpress/wp-content/uploads/2013/11/WorkSpreadsheet.csv
Also in the wp_postmeta table the value for meta_key “_wp_attached_file” when uploaded via the wordpress interface is with hyphens added and the relative folder path: 2013/11/Work-Spreadsheet.csv
Where as for uploads via my code its without the folder path and the file name is unmodified from my original: Work Spreadsheet.csv
Can anyone assist as to why this might be occurring? The code just before I use wp_insert_attachment() is below as a reference.. Just to say; I’ve tried with other file types such as images in case it was anything to do with uploading text files but the results are the same.
$attachment = array(
'guid' => $upload_dir_array['url'] . '/' . basename( $destination_name ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/.[^.]+$/', '', basename($destination_name)),
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $destination_name );
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id,$upload_dir.$destination_name );
wp_update_attachment_metadata( $attach_id, $attach_data );
So I figured this out.
The function wp_insert_attachment() sanitizes file names parsed to it. In the process it was removing spaces in filenames. To avoid this I did my own sanitization (still using WP functions) before parsing the filenames.
I renamed my files using sanitize_file_name() and this added hyphens (what I desired really) into all teh spaces in the names. Then later in the code when I parse the details to wp_insert_attachment() no alteration of the file names occur and they stay with the hyphens.