Last active
March 16, 2018 05:48
-
-
Save mklasen/e4de3af6e861f4d42e2613a64a114101 to your computer and use it in GitHub Desktop.
Link image to after uploading to /wp/v2/media (do an action after attachment has been inserted, use $request parameters)
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
<?php | |
add_action('rest_insert_attachment', function($attachment, $request, $creating) { | |
$data = $request->get_params(); // Extra data that was sent to /wp/v2/media | |
// In this example we can use $data['entry_id'] | |
// Something like: update_post_meta((int) $data['entry_id'], 'attachment_id', $attachment['ID']); | |
}); | |
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
<?php | |
// Include jQuery and wp-api | |
add_action('wp_enqueue_script', function()) { | |
wp_enqueue_script('upload-', plugin_dir_url(__FILE__).'assets/js/script.js', array('jquery', 'wp-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 file = ''; // your filelist from file input | |
var entry_id = 0 // some data to attach | |
// Prepare the form element | |
var formData = new FormData(); | |
formData.append( 'file', file ); // probably should pick a file to upload | |
formData.append( 'entry_id', entry_id ); // | |
jQuery.ajax({ | |
url: wpApiSettings.root + 'wp/v2/media', | |
method: 'POST', | |
processData: false, | |
contentType: false, | |
beforeSend: function(xhr) { | |
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); | |
}, | |
data: formData, | |
success: function(data) { | |
console.log(data) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment