Skip to main content
null đź’» notes

dropzone.js WordPress Integration Tutorial

Over on the Hacks forum at WordPress.org, user Manwoll was looking for a way to add drag-and-drop functionality to a contact form in WordPress. Not a fan of commercial contact form products myself, I sought out a method of doing this that would most accomodate a theme developer who is working on a custom solution for a client. The solution involves using dropzone.js and some basic PHP, and the end-state is a fully-functioning drag-and-drop box on a WordPress page that uploads files straight to your WP uploads directory.

The Problem #

Standard WordPress upload forms and functionality are limited to basic file upload features, like when you click on the “Select files” button in a box. We need a customized solution that will give us the ability to do the following:

The Solution #

If you want a drag-and-drop section to upload files on a publicly-accessible page (like a contact page) then you could use dropzone.js.

I spent four hours this morning trying to get Dropzone to integrate into WordPress, and I think I found the solution. I had working example that I can put back up if someone is interested.

The form works perfectly and uploads the dropped files into my current uploads folder (wp-content/uploads/2013/06/%filename%). My demo link will not upload files because I don’t want people uploading malicious code. I’ve commented out the function, and all you have to do is uncomment it when you put it into your file.

Here’s what I did:

<?php if(is_page('dropzone-wordpress-integration')): ?> <script src="<?php echo get_bloginfo('template_directory'); ?>/dropzone/dropzone.js"></script> <?php endif; ?>
<?php
  if($_POST['submitted'] == 1): // Form has been upploaded

    $upload_dir = wp_upload_dir();
    $upload_path = $upload_dir['path'] . DIRECTORY_SEPARATOR;
    $num_files = count($_FILES['file']['tmp_name']);

    echo "Uploading files to $upload_path...<br/>";

    if (!empty($_FILES)) {

        $tempFile = $_FILES['file']['tmp_name'];

        $targetPath = $upload_path;

        $targetFile = $targetPath . $_FILES['file']['name'];

        //I've commented this to prevent people from uploading malicious things to my site.
        // You'll want to uncomment it before you use it.
        //move_uploaded_file($tempFile, $targetFile);

    }

    echo "All done! We'll review your files momentarily.";

    endif;
?>

<div id="fancy-contact-form">
  <form action="<?php the_permalink(); ?>" method="post" class="dropzone dz-clickable" enctype="multipart/form-data">
    <div class="dz-default dz-message"><span>Drop files here to upload</span></div>
    <input type="hidden" name="submitted" value="1">
    <p align="right"><input type="Submit" value="Upload files"></p>
  </form>
</div>
</li>
</ul>

Again, check out the working example over on my blog (click here). I’ll keep it up as long as you need.

Future Considerations #