Skip to content

Instantly share code, notes, and snippets.

@hsleonis
Last active April 6, 2018 05:43
Show Gist options
  • Save hsleonis/0246e4c757156066f4dd9b80b9ebdb07 to your computer and use it in GitHub Desktop.
Save hsleonis/0246e4c757156066f4dd9b80b9ebdb07 to your computer and use it in GitHub Desktop.
WP save attachment with AJAX
<div id="tmx-image" data-img="<?php echo wp_get_attachment_url( $_GET['attachment_id'] ); ?>">
</div>
<script>
var tmx_img = $('#tmx-image').data('img');
$('#tmx-save').on('click',function(){
Caman("#tmx-image",tmx-image, function () {
// this = formatted image using Caman JS for example
var new_image = this.toBase64();
$('#tmx-loader').show();
//save To Server
var data = {
'action': 'tmx_save_image',
'old_image': tmx_img,
'new_image': new_image,
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
if("error" != response ){
window.location = response;
}
else {
alert('Image not saved!');
}
});
});
});
</script>
<?php
// Run the action at 'admin_init'
add_action( 'admin_init', array( $this, 'init' ) );
public function init(){
// Hook another action, so we can call it from JS
add_action('wp_ajax_tmx_save_image', array( $this,'easy_image_filters_save_image_ajax_callback') );
}
public function wp_ajax_tmx_save_image_ajax_callback() {
$uploads = wp_upload_dir();
$filetype_info = wp_check_filetype( $_POST['old_image'] );
$file_type = $filetype_info['type'];
$file_ext = $filetype_info['ext'];
// Easy, send the new image in POST['new_image'] in Base64 format
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $_POST['new_image']));
$filename = basename( $_POST['old_image'] );
$filename = wp_unique_filename( $uploads['path'], $filename );
$saved_file = file_put_contents($uploads['path'] . "/" .$filename, $data);
$attachment = array(
'post_mime_type' => $file_type,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $uploads['url'] . "/" .$filename
);
$attach_id = wp_insert_attachment( $attachment, $uploads['url'] . "/" . $filename, 0 );
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $uploads['path'] . "/" . $filename );
$success = wp_update_attachment_metadata( $attach_id, $attach_data );
if( $success ){
echo add_query_arg( 'item', $attach_id, admin_url('upload.php') );
}else{
echo 'error';
}
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment