Skip to content

Instantly share code, notes, and snippets.

@soderlind
Last active March 27, 2024 19:38
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save soderlind/38bb3abe89f1fc417827 to your computer and use it in GitHub Desktop.
Save soderlind/38bb3abe89f1fc417827 to your computer and use it in GitHub Desktop.
DropzoneJS & WordPress REST API
About:
The plugin provides drag’n’drop file uploads and uses the wp rest api to upload the file.
Installation:
Save dropzonejs-wp-rest-api.php in wp-content/plugins/dropzonejs-wp-rest-api/
Save dropzonejs-wp-rest-api.js in wp-content/plugins/dropzonejs-wp-rest-api/js/
Use:
After activating the plugin, add the [dropzonerest] shortcode to a post
Credits:
http://www.dropzonejs.com/
https://github.com/WP-API/WP-API, I learned a lot reading the wp-api source
Copyright:
The plugin is copyright Per Soderlind - per@soderlind.no
License: GPL, please feel free to modify the plugin as long as you make it GPL
/*
Uploading images is a two step process (from https://github.com/WP-API/WP-API/issues/1768#issuecomment-160540932):
POST the data to /wp/v2/media - this can either be as the request body, or in multipart format. This will upload the file, and give you a 201 Created response with a Location header. This header points to the post object for the attachment that has just been created.
PUT the post data to the endpoint returned in the Location header (which will look something like /wp/v2/media/{id}).
I do step 2 (PUT), if POST is a success, in myDropzone.on("success", function(file, response){}
*/
// dropzoneWordpressRestApiForm is the configuration for the element that has an id attribute
// with the value dropzone-wordpress-rest-api-form (or dropzoneWordpressRestApiForm)
Dropzone.options.dropzoneWordpressRestApiForm = {
//acceptedFiles: "image/*", // all image mime types
acceptedFiles: ".jpg", // only .jpg files
maxFiles: 1,
uploadMultiple: false,
maxFilesize: 5, // 5 MB
init: function() {
console.group('dropzonejs-wp-rest-api:');
var myDropzone = this; // closure
myDropzone.on("sending", function(file, xhr, data) {
console.log("file: %O", file);
//add nonce, from: http://v2.wp-api.org/guide/authentication/
xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
});
// myDropzone.on("processing", function(file) {
// this.options.url = WP_API_Settings.root + 'wp/v2/media/';
// });
myDropzone.on("error", function(file, error, xhr) {
console.error("ERROR: %o", error);
console.groupEnd();
});
myDropzone.on("success", function(file, response) {
console.log("success: %O", response);
var id = response.id; // media ID
// from: http://blog.garstasio.com/you-dont-need-jquery/ajax/
var xhr = new XMLHttpRequest();
xhr.open('PUT', WP_API_Settings.root + 'wp/v2/media/' + id);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
xhr.onload = function() {
if (xhr.status === 200) {
var userInfo = JSON.parse(xhr.responseText);
console.log("put: %O", userInfo);
console.groupEnd();
}
};
xhr.send(JSON.stringify({
title: {
raw: WP_API_Settings.title,
rendered: WP_API_Settings.title
},
description: WP_API_Settings.description,
alt_text: WP_API_Settings.alt_text,
caption: WP_API_Settings.caption
}));
});
}
};
<?php
/*
Plugin Name: DropzoneJS & WordPress REST API
Version: 0.0.1
Description: Demos how to upload files using DropzoneJS and the WordPress REST API (wp-api v2)
Author: Per Soderlind
Author URI: https://soderlind.no
Plugin URI: https://gist.github.com/soderlind/38bb3abe89f1fc417827#file-dropzonejs-wp-rest-api-php
License: GPL
*/
define( 'DROPZONEJS_WP_REST_API_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'DROPZONEJS_WP_REST_API_PLUGIN_VERSION', '0.0.1' );
add_action( 'plugins_loaded', 'dropzonejs_wp_rest_api_init' );
function dropzonejs_wp_rest_api_init() {
add_action( 'wp_enqueue_scripts', 'dropzonejs_wp_rest_api_enqueue_scripts' );
add_shortcode( 'dropzonerest', 'dropzonejs_wp_rest_api_shortcode' );
}
function dropzonejs_wp_rest_api_enqueue_scripts() {
wp_enqueue_script(
'dropzonejs',
'https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.2.0/min/dropzone.min.js',
array(),
DROPZONEJS_WP_REST_API_PLUGIN_VERSION
);
// Load custom dropzone javascript
wp_enqueue_script(
'dropzone-wp-rest',
DROPZONEJS_WP_REST_API_PLUGIN_URL . '/js/dropzonejs-wp-rest-api.js',
array( 'wp-api', 'dropzonejs' ),
DROPZONEJS_WP_REST_API_PLUGIN_VERSION
);
wp_enqueue_style(
'dropzonecss',
'https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.2.0/min/dropzone.min.css',
array(),
DROPZONEJS_WP_REST_API_PLUGIN_VERSION
);
// from: http://v2.wp-api.org/guide/authentication/
wp_enqueue_script( 'wp-api' );
wp_localize_script(
'wp-api',
'WP_API_Settings',
array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' ),
'title' => 'Media Title',
'description' => 'Media Description',
'alt_text' => 'Media Alt Text',
'caption' => 'Media Caption'
)
);
}
// Add Shortcode
function dropzonejs_wp_rest_api_shortcode( $atts ) {
//user can ?
if ( ! is_user_logged_in() || !current_user_can( 'upload_files' ) ) {
return;
}
$url = rest_url() . 'wp/v2/media/'; // dropzonejs will not accept an empty url
return <<<ENDFORM
<div id="dropzone-wordpress-rest-api"><form action="$url" class="dropzone needsclick dz-clickable" id="dropzone-wordpress-rest-api-form">
<div class="dz-message needsclick">
Drop files here or click to upload.<br>
<span class="note needsclick">(Files are uploaded to uploads/yyyy/mm)</span>
</div>
<input type='hidden' name='action' value='submit_dropzonejs'>
</form></div>
ENDFORM;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment