Forked from cyberwani/wordpress-upload-base64.php
Last active
February 2, 2022 22:44
-
-
Save OussamaKhoubran/f5d9f5014c4a41b9b50e919813d6ccf8 to your computer and use it in GitHub Desktop.
Upload a base64 string as image to the WordPress media library
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 | |
/** | |
* 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/png;base64,', '', $base64_img ); | |
$img = str_replace( ' ', '+', $img ); | |
$decoded = base64_decode( $img ); | |
$filename = $title . '.png'; | |
$file_type = 'image/png'; | |
$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); | |
$attach_data = wp_generate_attachment_metadata($attach_id, $upload_dir['path'] . '/' . $hashed_filename); | |
wp_update_attachment_metadata($attach_id, $attach_data); | |
return $attach_id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment