Upload ảnh với Ajax ngoài Front-end WordPress

/****************************************************************
Project: MySavingWallet
Resource: http://www.ibenic.com/wordpress-file-upload-with-ajax/ 

HTML FORM 
*****************************************************************/

<dt><?php esc_html_e( 'Support Doc', 'listify_child' ); ?></dt>
<dd>
  <section>
      <label for="async-upload" class="input">
          <i class="icon_append fa fa-life-ring"></i>
          <input type="file" id="bank_docs">
          <input type="hidden" name="image_id" class="image_id">
          <p>Please upload a proof of bank account ownership, <br> acceptable forms of verification are voided check, <br> bank letter, or bank statement.</p>
      </label>
  </section>
</dd>
<dd>
  <section>
      <ul id="preview_doc">
      </ul>
  </section>
</dd>
      
      
      
 /****************************************************************
JavaScript / AJAX 
*****************************************************************/

SavingWallet = {};

SavingWallet.prototype.prepareUpload = function (e) {
		e.preventDefault();
		var file = e.target.files;
		var data = new FormData();
		var nonce = $("#_wpnonce").val();
		data.append('action', 'upload_bank_doc');
		//data.append('nonce', local.nonce);
		$.each(file, function(k, v) {
			data.append('upload_bank_doc', v);
		});

    	$.ajax({
    		  url: local.ajax_url,
	          type: 'POST',
	          data: data,
	          cache: false,
	          dataType: 'json',
	          processData: false,
	          contentType: false,
	          success: function(data, textStatus, jqXHR) {	
	          	console.log(data);
              	if( data.response == "SUCCESS" ){
	                var preview = "";
	                if( data.type === "image/jpg" 
	                  || data.type === "image/png" 
	                  || data.type === "image/gif"
	                  || data.type === "image/jpeg"
	                ) {
	                  preview = "<li data-attachment-id='" + data.id + "'><img src='" + data.url + "' /><span class=\"delete_doc\" data-fileurl='" + data.url + "'>x</span></li>";
	                } else {
	                  preview = "<li data-attachment-id='" + data.id + "'><a href='" + data.url + "'>" + data.filename + "</a></li>";
	                }
	  
	                var previewID = $('#preview_doc');
	                previewID.append(preview);
                
                 } else {
                 	$('.add_bank_message').css('color', 'red').text(data.error);
                 }
			}
		})
    };
    
 	var savingwallet = new SavingWallet();
  $('#bank_docs').on('change', savingwallet.prepareUpload);
 
 
/****************************************************************
PHP Processing .... 
*****************************************************************/

function upload_bank_doc_func() {
    $usingUploader = 2;
    $fileErrors = array(
        0 => "There is no error, the file uploaded with success",
        1 => "The uploaded file exceeds the upload_max_files in server settings",
        2 => "The uploaded file exceeds the MAX_FILE_SIZE from html form",
        3 => "The uploaded file uploaded only partially",
        4 => "No file was uploaded",
        6 => "Missing a temporary folder",
        7 => "Failed to write file to disk",
        8 => "A PHP extension stoped file to upload" );
    $posted_data =  isset( $_POST ) ? $_POST : array();
    $file_data = isset( $_FILES ) ? $_FILES : array();
    $data = array_merge( $posted_data, $file_data );
   // check_ajax_referer( 'add_bank_docs_nonce', 'nonce' );
    $response = array();
    if( $usingUploader == 1 ) {
        $uploaded_file = wp_handle_upload( $data['upload_bank_doc'], array( 'test_form' => false ) );
        if( $uploaded_file && ! isset( $uploaded_file['error'] ) ) {
            $response['response'] = "SUCCESS";
            $response['filename'] = basename( $uploaded_file['url'] );
            $response['url'] = $uploaded_file['url'];
            $response['id'] = $uploaded_file['id'];
            $response['type'] = $uploaded_file['type'];
        } else {
            $response['response'] = "ERROR";
            $response['error'] = $uploaded_file['error'];
        }
    } elseif ( $usingUploader == 2) {
        $attachment_id = media_handle_upload( 'upload_bank_doc', 0 );
        
        if ( is_wp_error( $attachment_id ) ) { 
            $response['response'] = "ERROR";
            $response['error'] = $fileErrors[ $data['upload_bank_doc']['error'] ];
        } else {
            $fullsize_path = get_attached_file( $attachment_id );
            $pathinfo = pathinfo( $fullsize_path );
            $url = wp_get_attachment_url( $attachment_id );
            $response['response'] = "SUCCESS";
            $response['filename'] = $pathinfo['filename'];
            $response['id'] = $attachment_id;
            $response['url'] = $url;
            $type = $pathinfo['extension'];
            if( $type == "jpeg"
            || $type == "jpg"
            || $type == "png"
            || $type == "gif" ) {
                $type = "image/" . $type;
            }
            $response['type'] = $type;
        }
    }
    echo json_encode( $response );
    die();
}

add_action("wp_ajax_upload_bank_doc", "upload_bank_doc_func");

 

Xem thêm  Lấy youtube video ID và vimeo video ID từ Url