Ajax image upload wordpress frontent - codex

Latest

Coding help in website development.

BANNER 728X90

Friday 29 April 2016

Ajax image upload wordpress frontent

First Step:

Past this code in your Page-

<div class = "upload-form">
        <div class = "form-group">
          <label><?php __('Select Files:', 'cvf-upload'); ?></label>
          <input type = "file" id="files" name="my_file_upload[]" accept = "image/*" class = "files-data            form-control" multiple />
       </div>
</div>



Second Step:


Past this jquery code in your same page:

<script>
$(document).ready(function() {

    $('body').on('change', '.files-data', function(e){
        e.preventDefault;
  
        var fd = new FormData();
        var files_data = $('.upload-form .files-data'); 
     
        $.each($(files_data), function(i, obj) {
            $.each(obj.files,function(j,file){
                fd.append('my_file_upload[' + j + ']', file);
            })
        });
        
        fd.append('action', 'cvf_upload_files');   

  var image_gallery=document.getElementById('image_gallery').value;
        
        fd.append('post_id', ''); 
  fd.append('image_gallery',image_gallery); 
  
        $.ajax({
            type: 'POST',
            url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
            data: fd,
            contentType: false,
            processData: false,
   dataType: "json",
            success: function(response){ 
    
    $('#image_gallery').val(response['attachment_idss']);
     
            }
        });
    });
});
</script> 


Third Step:


Past this code in "function.php" file-


add_action('wp_ajax_cvf_upload_files', 'cvf_upload_files');
add_action('wp_ajax_nopriv_cvf_upload_files', 'cvf_upload_files'); // Allow front-end submission 

function cvf_upload_files(){
    

  /* img upload */

 $condition_img=7;
 $img_count = count(explode( ',',$_POST["image_gallery"] )); 

 if(!empty($_FILES["my_file_upload"])){

 require_once( ABSPATH . 'wp-admin/includes/image.php' );
 require_once( ABSPATH . 'wp-admin/includes/file.php' );
 require_once( ABSPATH . 'wp-admin/includes/media.php' );
  
   
 $files = $_FILES["my_file_upload"];  
 $attachment_ids=array();
 $attachment_idss='';

 if($img_count>=1){
 $imgcount=$img_count;
 }else{
 $imgcount=1;
 }
  

 $ul_con='';

 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 ("my_file_upload" => $file); 
    
    
    foreach ($_FILES as $file => $array) {              
      
      if($imgcount>=$condition_img){ break; } 

     require_once(ABSPATH . "wp-admin" . '/includes/image.php');
     require_once(ABSPATH . "wp-admin" . '/includes/file.php');
     require_once(ABSPATH . "wp-admin" . '/includes/media.php');
     
     //$newupload = my_handle_attachment($file,$pid); 

     $attach_id = media_handle_upload( $file, $post_id );
      $attachment_ids[] = $attach_id; 

      $image_link = wp_get_attachment_image_src( $attach_id, apply_filters( 'easy_image_gallery_linked_image_size', 'thumbnail' ) );
    $ul_con.='<div id="li_'.$attach_id.'"><img   src="'.$image_link[0].'"  class="thumb "><br>
           <a onclick="remove_img('.$attach_id.')" href="javascript:;" class="delete check">Remove</a> 
      </div>'; 
      
    }
    if($imgcount>$condition_img){ break; } 
    $imgcount++;
   } 
  }

  
 } 
/*img upload */

 $image_gallery=$_POST['image_gallery'];

$attachment_idss = array_filter( $attachment_ids  );
$attachment_idss =  implode( ',', $attachment_idss );  

 if($image_gallery){ $attachment_idss=$image_gallery.",".$attachment_idss;  }


$arr = array();
$arr['attachment_idss'] = $attachment_idss;
$arr['ul_con'] =$ul_con; 

echo json_encode( $arr );
 die();

}


Description:


You can upload image on wordpress frontend with the help of this code.

Here in "first step" is simple html code use to upload file.

In "Second step" is jquery file

  •  to pass any variable with value use "  fd.append('variable', 'variable value');   "
  • To check response use alert function.

In "Third step" this is php code to use as ajax file can be check response to use "print_r($_REQUEST)" OR "print_r($_FILES)".


IF ANY ERROR:
{
  •  First check form "enctype"
  • check "$" OR "jquery" error in jquery code.
  • Please check jquery library file must be included.
  • before HTML code add  php code :
                    require_once( ABSPATH . 'wp-admin/includes/image.php' );
                    require_once( ABSPATH . 'wp-admin/includes/file.php' );
                    require_once( ABSPATH . 'wp-admin/includes/media.php' );
}





HOPE THIS WILL HELP YOU. 

5 comments:

  1. Replies
    1. seems to work but how send the file to the media library?

      Delete
  2. The files are in the media library, it works and helps, thank you!

    ReplyDelete
  3. Can you explain more about the "image_gallery" in the sentence var image_gallery=document.getElementById('image_gallery').value;
    I am a bit difficult to determine the mean of this context. Thank you

    ReplyDelete