Skip to content

Instantly share code, notes, and snippets.

@modemlooper
Created January 9, 2019 19:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save modemlooper/18ebe2286949c05409a47ccefe46df99 to your computer and use it in GitHub Desktop.
Save modemlooper/18ebe2286949c05409a47ccefe46df99 to your computer and use it in GitHub Desktop.
Upload a base64 string as image to the WordPress media library
/**
* 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