Created
February 11, 2017 12:30
-
-
Save mklasen/1aae73fa5650acd64476b2ed81a45da3 to your computer and use it in GitHub Desktop.
Upload files to WordPress with ajax via REST API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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