Hope I'm in the right place here.
I've seen some file upload plugins but they aren't quite what I want.
I already have a child theme setup and have added and removed fields from checkout page.
Now during the checkout page, I also want to add a file upload box for pdf, docx etc.
I've added a function and hooked the action and it shows up on screen (code from examples below).
But it doesn't seem to actually upload the file to the server.
I'm hoping someone can point me in the right direction to handle this better.
I'd like the files to be stored uniquely to each user some how.
And I'd like to be able to either link to the file from the Woocommerce order view, or to be able to attach it to the order email (whatever is easier).
Appreciate any help, or to point me somewhere more appropriate for this.
//--FILE UPLOAD:
//--display on screen:
function upload_file() {
echo '<div id="my_custom_checkout_field"><h2>'.__('File Upload').'</h2>';
//--
wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');
$html = '<p class="description">';
$html .= 'Upload your PDF here.';
$html .= '</p>';
$html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25">';
echo $html;
//--
echo '</div>';
}
add_action('woocommerce_after_order_notes', 'upload_file');
//--save the file to disk:
function save_custom_meta_data($id) {
/* --- security verification --- */
if(!wp_verify_nonce($_POST['wp_custom_attachment_nonce'], plugin_basename(__FILE__))) {
return $id;
} // end if
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $id;
} // end if
if('page' == $_POST['post_type']) {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} else {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} // end if
/* - end security verification - */
// Make sure the file array isn't empty
if(!empty($_FILES['wp_custom_attachment']['name'])) {
// Setup the array of supported file types. In this case, it's just PDF.
$supported_types = array('application/pdf');
// Get the file type of the upload
$arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
$uploaded_type = $arr_file_type['type'];
// Check if the type is supported. If not, throw an error.
if(in_array($uploaded_type, $supported_types)) {
// Use the WordPress API to upload the file
$upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));
if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
} else {
add_post_meta($id, 'wp_custom_attachment', $upload);
update_post_meta($id, 'wp_custom_attachment', $upload);
} // end if/else
} else {
wp_die("The file type that you've uploaded is not a PDF.");
} // end if/else
} // end if
} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');