Skip to content

Instantly share code, notes, and snippets.

@huubl
Forked from cyberwani/wordpress-upload-base64.php
Created October 27, 2022 17:39
Show Gist options
  • Save huubl/c15a0a85b85c9ab18ea12503f3e620ef to your computer and use it in GitHub Desktop.
Save huubl/c15a0a85b85c9ab18ea12503f3e620ef to your computer and use it in GitHub Desktop.
Upload a base64 string as image to the WordPress media library
<?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