Skip to content

Instantly share code, notes, and snippets.

@mklasen
Created February 11, 2017 12:30
Show Gist options
  • Save mklasen/1aae73fa5650acd64476b2ed81a45da3 to your computer and use it in GitHub Desktop.
Save mklasen/1aae73fa5650acd64476b2ed81a45da3 to your computer and use it in GitHub Desktop.
Upload files to WordPress with ajax via REST API
var data = new FormData()
// Add data/files to formdata var
jQuery.ajax({
url: wpApiSettings.root + 'routehere/v1/subroute/save',
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: (data) => {
console.log('succes')
console.log(data)
}
})
// For a GIST
add_action( 'rest_api_init', function () {
// Register route
register_rest_route( 'routehere/v1', '/subroute/save', array(
'methods' => 'POST',
'callback' => function ( WP_REST_Request $request ) {
// Prepare array for output
$output = array();
// Request the data send
$sendData = $request->get_params();
// Identify user
$user = wp_get_current_user();
// Which user is logged in?
$userID = $user->ID;
// Get the upload files
$files = $request->get_file_params();
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Process images
if (!empty($files)) {
$upload_overrides = array( 'test_form' => false );
foreach ($files as $key => $file) {
$attachment_id = media_handle_upload( $key, $challengeID );
if ( is_wp_error( $attachment_id ) ) {
$output['status'] = 'error';
$output['message'] = '- The image could not be uploaded.';
return $output;
} else {
// Success
$output['status'] = 'success';
$output['message'] = 'File '.$attachment_id.' uploaded.';
}
}
}
return $output;
}
));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment