Last active
October 13, 2017 18:31
-
-
Save kodie/0342e1a1f59cdafddd59e697af0605e4 to your computer and use it in GitHub Desktop.
This file contains 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 | |
function base64_upload($base64, $filename = null) { | |
if (!$filename) $filename = md5($base64); | |
if (!pathinfo($filename, PATHINFO_EXTENSION)) $filename .= '.jpg'; | |
$content = base64_decode($base64); | |
$upload_dir = wp_upload_dir(); | |
$file = $upload_dir['path'] . DIRECTORY_SEPARATOR . $filename; | |
file_put_contents($file, $content); | |
$mime_info = wp_check_filetype_and_ext($file, $filename); | |
if ($mime_info['proper_filename']) $filename = $mime_info['proper_filename']; | |
$file_info = array( | |
'name' => $filename, | |
'type' => $mime_info['type'], | |
'tmp_name' => $file, | |
'error' => 0, | |
'size' => strlen($content) | |
); | |
$overrides = array( | |
'test_form' => false, | |
'test_size' => true | |
); | |
$result = wp_handle_sideload($file_info, $overrides); | |
if (empty($result['error'])) { | |
$attachment = array( | |
'guid' => $result['file'], | |
'post_mime_type' => $mime_info['type'], | |
'post_title' => $filename, | |
'post_content' => '', | |
'post_status' => 'inherit' | |
); | |
$result['id'] = wp_insert_attachment($attachment, $result['file']); | |
$result['metadata'] = wp_generate_attachment_metadata($result['id'], $result['file']); | |
wp_update_attachment_metadata($result['id'], $result['metadata']); | |
} | |
return $result; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment