Created
September 13, 2019 10:19
-
-
Save cyberwani/ad5452b040001878d692c3165836ebff 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/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 ); | |
} |
Can anyone help a newbie?
Where should one put this code? on functions.php? wp-config? at a theme file?
Would that help to upload base64 images to wordpress through rest api as well?
Thakns community
if you are modifying the product API response of wooCommerce, you should handle it using woocomerce product hooks by
- creating a class
- init hooks in constructor
- lastly in the method that you are calling put the snippet
that's it, have a good day mate
Thanks a lot!
thanks a lot. It works for me. I use this to handle image base64 data from API requests.
Someone tryed to do that to enable paste images on activity feed ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you you provide a good start for me .
I improve your function for using all images that are supported by WP also PNG, GIF , WEBP
The filename will be generated by WP and make sure is unique for upload_path in the way WP is doing it .
Also there is option to resize image and set max dpi
You can update yours in case you want .. so people can use it
Not tested on Windows .. in case i put the right way DIRECTORY_SEPARATOR