-
-
Save manidip/735d3443a40823c824535961108e486b to your computer and use it in GitHub Desktop.
Upload a base64 string as image to the WordPress media library
This file contains 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 | |
/** | |
* Save the image on the server. | |
*/ | |
function save_image( $base64_img, $title ) { | |
// Upload dir. | |
$upload_dir = wp_upload_dir(); | |
$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR; | |
$img = str_replace( 'data:image/jpeg;base64,', '', $base64_img ); | |
$img = str_replace( ' ', '+', $img ); | |
$decoded = base64_decode( $img ); | |
$filename = $title . '.jpeg'; | |
$file_type = 'image/jpeg'; | |
$hashed_filename = md5( $filename . microtime() ) . '_' . $filename; | |
// Save the image in the uploads directory. | |
$upload_file = file_put_contents( $upload_path . $hashed_filename, $decoded ); | |
$attachment = array( | |
'post_mime_type' => $file_type, | |
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $hashed_filename ) ), | |
'post_content' => '', | |
'post_status' => 'inherit', | |
'guid' => $upload_dir['url'] . '/' . basename( $hashed_filename ) | |
); | |
$attach_id = wp_insert_attachment( $attachment, $upload_dir['path'] . '/' . $hashed_filename ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment