Skip to main content

AJAX single file upload wordpress

<form method="post" enctype="multipart/form-data">
   <div class="form-group">
      <label>Choose File:</label>
      <input type="file" id="file" />
   </div>
</form>
 
<script>
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
    jQuery(function($) {
        $('body').on('change', '#file', function() {
            var file_data = $(this).prop('files')[0];
            var form_data = new FormData();
            form_data.append('file', file_data);
            form_data.append('action', 'file_upload');
 
            jQuery.ajax({
                url: ajaxurl,
                type: 'POST',
                contentType: false,
                processData: false,
                data: form_data,
                success: function (response) {
                    alert('File uploaded successfully');
                }
            });
        });
    });
</script>
 
functions.php--

add_action( 'wp_ajax_file_upload', 'file_upload_callback' );
add_action( 'wp_ajax_nopriv_file_upload', 'file_upload_callback' );
 
function file_upload_callback() {
   $upload = wp_upload_bits($_FILES["file"]["name"], null, file_get_contents($_FILES["file"]["tmp_name"]));
   wp_die();
}
 
 

Comments

Popular posts from this blog

add custom post type

/**  *  * add custom post type  *  */ function my_custom_post_product() {   $labels = array(     'name'               => _x( 'Products', 'post type general name' ),     'singular_name'      => _x( 'Product', 'post type singular name' ),     'add_new'            => _x( 'Add New', 'book' ),     'add_new_item'       => __( 'Add New Product' ),     'edit_item'          => __( 'Edit Product' ),     'new_item'           => __( 'New Product' ),     'all_items'          => __( 'All Products' ),     'vi...

Toolset conditional

[wpv- if evaluate= "'[wpv-current-user info='id']' = '[wpv-post-author format='meta' meta='ID']' OR '[wpv-current-user info='role']' = 'administrator'" ]      //the content you want to hide goes here [/wpv- if ]