Skip to content

Instantly share code, notes, and snippets.

@yawalkar
Last active September 26, 2022 14:39
Show Gist options
  • Save yawalkar/49f4960d35906564a5f52ff48395df13 to your computer and use it in GitHub Desktop.
Save yawalkar/49f4960d35906564a5f52ff48395df13 to your computer and use it in GitHub Desktop.
Upload base64 encoded image to WordPress using FlowMattic
<?php
/**
* Save the base64 encoded image in WP.
*
* @param string $title Image title without extension.
* @param string $base64_img Base64 encoded image string.
*/
function flowmattic_save_base64_image( $title, $base64_img ) {
// Upload dir.
$upload_dir = wp_upload_dir();
$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
$image_parts = explode( ',', $base64_img );
$img_part_1 = str_replace( 'data:image/', '', $image_parts[0] );
$image_decode = base64_decode( $image_parts[1] );
$mime = str_replace( ';base64', '', $img_part_1 );
$file_type = 'image/' . $mime;
if ( 'svg+xml' === $mime ) {
$mime = 'svg';
}
// Set the file name with image extension.
$filename = $title . '.' . $mime;
$hashed_filename = md5( $filename . microtime() ) . '_' . $filename;
// Save the image in the uploads directory.
$upload_file = file_put_contents( $upload_path . $filename, $image_decode );
$attachment = array(
'post_mime_type' => $file_type,
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit',
'guid' => $upload_dir['url'] . '/' . $filename,
);
// Insert attachment for use in WP.
$image_id = wp_insert_attachment( $attachment, $upload_dir['path'] . '/' . $filename );
// Return the image attachment post ID.
return array(
'image_id' => $image_id,
'image_url' => wp_get_attachment_url( $image_id, 'full' ),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment