Skip to content

Instantly share code, notes, and snippets.

@ravahdati
Last active November 13, 2020 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravahdati/e02520b39ab92c55cb08adf089d952a7 to your computer and use it in GitHub Desktop.
Save ravahdati/e02520b39ab92c55cb08adf089d952a7 to your computer and use it in GitHub Desktop.
Upload base64 images to wordpress upload directory
<?php
function tidaweb_upload_base64_image( $base64_image_data, $base64_file_name )
{
// check and get path of upload directory
$upload_dir = wp_upload_dir();
$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
$img = $base64_image_data;
if(strpos($img, 'image/jpg') !== false)
{
$file_extension = "jpg";
$file_type = "image/jpg";
$img = str_replace('data:image/jpg;base64,', '', $img);
}
elseif(strpos($img, 'image/jpeg') !== false)
{
$file_extension = "jpg";
$file_type = "image/jpg";
$img = str_replace('data:image/jpeg;base64,', '', $img);
}
else
{
$file_extension = "png";
$file_type = "image/png";
$img = str_replace('data:image/png;base64,', '', $img);
}
$img = str_replace(' ', '+', $img);
$decoded = base64_decode($img) ;
$file_name = sanitize_file_name( $base64_file_name ). '.' . $file_extension;
$hashed_filename = md5( $file_name . microtime() ) . '-' . $file_name;
// create file on upload directory
$image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded );
//HANDLE UPLOADED FILE
if( !function_exists( 'wp_handle_sideload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
// @new file
$file = array();
$file['error'] = '';
$file['tmp_name'] = $upload_path . $hashed_filename;
$file['name'] = $hashed_filename;
$file['type'] = $file_type;
$file['size'] = filesize( $upload_path . $hashed_filename );
// upload file to server
// @new use $file instead of $image_upload
$uploaded_file = wp_handle_sideload( $file, array( 'test_form' => false ) );
if(empty($uploaded_file['error']))
{
$filename = $uploaded_file['file'];
$attachment = array(
'post_mime_type' => $uploaded_file['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', sanitize_file_name( $base64_file_name )),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $upload_dir['url'] . '/' . sanitize_file_name( $base64_file_name )
);
$attach_id = wp_insert_attachment( $attachment, $filename );
if(!is_wp_error($attach_id))
{
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
return [
'attach_id' => $attach_id,
'attach_url' => wp_get_attachment_image_src( $attach_id, 'full' )[0]
];
}
else
{
return [
'error' => __('Error when uploading image.')
];
}
}
else
{
return [
'error' => $uploaded_file['error']
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment