Ajax WordPress
Ajax media upload in WordPress
10 August, 2016
0

I was looking for a method to upload media file in WP over internet. There is a function “wp_handle_upload” to do this task. But this actually can do upload media using the file key name, not PHP FILES variable. But we can only pass variables in a ajax request. So this function is not appropriate for ajax request.

Today, I’ll show how to upload files to media library using ajax request.

The HTML Form

<form id="form" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="submit">
</form>

Here, we have created a form, assigned an id “form” to it. Remember, “enctype” is mandatory for file upload in a form.

The JS

Create a js file named “ajax-upload” and keep it to your “theme_dir/js/” direcotry. Now, its the time to enqueue our js file. We also need to localize it to pass WP ajax url. Open your theme function.php file and copy the code below.

function enqueue_ajax_file_upload_scripts() {
    wp_enqueue_script('ajax-upload', get_template_directory_uri() . '/js/ajax-upload.js', array(), false, true);
    wp_localize_script('ajax-upload', 'object', ['ajaxurl' => admin_url('admin-ajax.php')]);
}
add_action('wp_enqueue_scripts', 'enqueue_ajax_file_upload_scripts');

We have created js file, and successfully enqueue it to our theme. Now, time to create ajax request. Open “ajax-upload” and copy the below code in it.

jQuery('#form').on('submit', function() {
    var formData = new FormData(jQuery(this)[0]);

    jQuery.ajax({
        url: object.ajaxurl + '?action=ajax_upload',
        type: 'POST',
        data: formData,
        success: function (data) {
            console.log(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
});

We are now sending our form data to a ajax method. Its time to handle the ajax request.

Handling Ajax Request

function ajax_upload() {
    // Including file library if not exist
    if (!function_exists('wp_handle_upload')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }

    // Uploading file to server
    $movefile = wp_handle_upload($_FILES['file'], ['test_form' => false]);

    // If uploading success & No error
    if ($movefile && !isset($movefile['error'])) {
        $filename = $movefile['file'];
        $filetype = wp_check_filetype(basename($filename), null);
        $wp_upload_dir = wp_upload_dir();

        $attachment = array(
            'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
            'post_mime_type' => $filetype['type'],
            'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
            'post_content' => '',
            'post_status' => 'inherit',
        );

        // Adding file to media
        $attach_id = wp_insert_attachment($attachment, $filename);

        // If attachment success
        if($attach_id) {
            require_once ABSPATH . 'wp-admin/includes/image.php';

            // Updating attachment metadata
            $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
            wp_update_attachment_metadata($attach_id, $attach_data);
        }

        echo 'Success!';
    } else {
        echo $movefile['error'];
    }

    die();
}
add_action('wp_ajax_ajax_upload', 'ajax_upload');

Here, we are uploading the file to server first. Then we are attaching the file to media library and generating metadata. Just copy the above function and paste it in your theme function.php file

That’s it! Now time to test it. Remember, we are allowing to insert any file. If you want to limit for image only add “accept=”image/*”” to input tag. And this is a basic ajax upload example, So you need many modification to use it on a production site.

6

About author

Sabuz

Related items

/ You may check this items as well

How to count facebook page likes in WordPress

I was looking for a method to upload media file in...

Read more