Hello @pbchambers26
First of all, you create a form. Then send the media to the Ajax action by making an Ajax call on its submission. Now with Ajax call-back function we can send attachments in an email and save them in the media library.
Here is the ajax call back function
function ajax_call_back_func() {
// File upload
if ( $_FILES ) {
$files = $_FILES["file"];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array ("file" => $file);
foreach ($_FILES as $file => $array) {
$attachment_details = upload_file_to_media_library( 'file', $file, $post_id );
if ( ! empty( $attachment_details['attach_id'] ) ) {
$attachments = get_attached_file( $attachment_details['attach_id'] );
}
$attachments_url[] = wp_get_attachment_url( $attachment_details['attach_id'] );
}
}
}
}
$headers = "X-Priority: 1\r\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$sent = wp_mail( $to_email, $to_subject, $content, $headers, $attachments_url );
}
function upload_file_to_media_library( $key = null, $files = array(), $post_id = 0 ) {
$result = array();
$result['success'] = 0;
$result['attach_id'] = 0;
if ( $_FILES[ $key ]['error'] !== UPLOAD_ERR_OK ) {
return $result;
}
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress handle the upload.
$attachment_id = media_handle_upload( $key, $post_id );
if ( ! is_wp_error( $attachment_id ) ) {
update_post_meta( $attachment_id, 'attachment_for', 'custom_admin_order_notes' );
$result = array();
$result['success'] = 1;
$result['attach_id'] = $attachment_id;
}
return $result;
}
I hope this code will help you.
if you have any doubt in jquery ajax then you can ask me here.
Thank you