Upload Image with Ajax in wordpress

Upload Image with Ajax in wordpress

The functions.php should have a code like this

Following code is used to localize the developer.js file

function developer_pro_scripts() {
wp_enqueue_style( 'developer_pro-style', get_stylesheet_uri(), array(), _S_VERSION );
wp_enqueue_style( 'font-awesome-style', 'https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css', array(), _S_VERSION );
wp_enqueue_style( 'stylemin-style', get_template_directory_uri().'/app/css/style.min.css', array(), _S_VERSION );
wp_deregister_script('jquery'); 
wp_enqueue_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', array(), _S_VERSION, true );
wp_enqueue_script( 'developer-js', get_template_directory_uri() . '/js/developer.js', array('jquery'), _S_VERSION, true );
$nationaltreasure = array(
	    'siteurl'        => site_url(),
	    'adminurl'       => admin_url(),
	    'ajaxurl'        => admin_url( 'admin-ajax.php' ),
	    'templateurl'    => get_template_directory_uri(),
	    'thank_you_page' => get_field('thank_you_page','option')
	);
wp_localize_script( 'developer-js', 'nationaltreasure', $nationaltreasure );
}
add_action( 'wp_enqueue_scripts', 'developer_pro_scripts' );

Following code is used to upload via AJAX

Strongly recommended you add NOUNCE for security purpose

add_action( 'wp_ajax_picture_upload', 'picture_upload_callback' );
add_action( 'wp_ajax_nopriv_picture_upload', 'picture_upload_callback' );
function picture_upload_callback(){
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
if(!empty($_FILES)){
        $headshot['name']      = $_FILES['object_pic']['name'];
        $headshot['type']      = $_FILES['object_pic']['type'];
        $headshot['tmp_name']  = $_FILES['object_pic']['tmp_name'];
        $headshot['error']     = $_FILES['object_pic']['error'];
        $headshot['size']      = $_FILES['object_pic']['size'];  
    }
	if( is_array($headshot) && count($headshot)>0)
	{  
	 	$uploadedfile       = $headshot;
		 $upload_chk_bypass  = array( 'test_form' => false );
		 $movefile = wp_handle_upload( $uploadedfile, $upload_chk_bypass );
		 if ( $movefile && !isset( $movefile['error'] ) )
		 {
		 //File is valid, and was successfully uploaded
		   $attachment = array(
		     'guid'           => $movefile['url'],
		     'post_mime_type' => $movefile['type'],
		     'post_title'     => preg_replace( '/\.[^.]+$/', '', $uploadedfile['name']  ),
		     'post_content'   => '',
		     'post_status'    => 'inherit'
		   );
		   $attachment_idh     =  wp_insert_attachment( $attachment, $movefile['file'],'');
		   $attach_data        =  wp_generate_attachment_metadata( $attachment_idh, $movefile['file'] );
		   wp_update_attachment_metadata( $attachment_idh, $attach_data );
		   $attachment_idh     = intval($attachment_idh);
		   $response           =  wp_get_attachment_image_src($attachment_idh, 'thumbnail' );
		   echo json_encode( array('profileimage'=> $response , 'attachmentid' =>  $attachment_idh ) );
		 }
	}
	wp_die();
}

The Javascript file should have something like this

/*Picture Upload to Media*/
  jQuery(document).on('change', '.photos', function(){
      var name        = jQuery(this).val();
      var currentid   = jQuery(this).attr('id') ;
      console.log(currentid);
      var form_data   = new FormData();
      var ext         = name.split('.').pop().toLowerCase();
      if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
      {
       alert("Please select your picture in (png,jpg,jpeg) extentions");
       jQuery(this).val('');
       return false;
      }
      var oFReader    = new FileReader();
      oFReader.readAsDataURL(document.getElementById(currentid).files[0]);
      var f           = document.getElementById(currentid).files[0];
      var fsize       = f.size||f.fileSize;
      if(fsize > 8000000)
      {
       alert("Please upload an Image less than 8MB in size.");
       jQuery(this).val('');
       return false;
      }
      else
      {
        form_data.append("object_pic", document.getElementById(currentid).files[0]);
        form_data.append("action", 'picture_upload');
          jQuery.ajax({
              url         :nationaltreasure.ajaxurl,
              method      :"POST",
              data        :form_data,
              contentType :false,
              cache       :false,
              processData :false,
              beforeSend  :function(){
                jQuery('.'+currentid).attr('src', nationaltreasure.templateurl+'/images/loader.gif');
              },  
              success     :function(data)
              {
               
                imgagedata = JSON.parse(data);
               
                var attachmentid  = imgagedata.attachmentid;
                var attachmentdata= imgagedata.profileimage;
               
                var imageurl      = attachmentdata[0];
                jQuery('#'+currentid+'id').val(attachmentid);
                jQuery('.'+currentid).attr('src', imageurl);
                
              }
           });
      }
    });
  /*Picture Upload to media */

The HTML form should have like this

Leave a Reply

Your email address will not be published. Required fields are marked *