I'm trying to convert a base64 string to an image file and upload it into WordPress media library.
It seems like the code is working, but, for some reason, every time I call this function it uploads the same image multiple times.. I wonder what am I doing wrong and what I need to change in order to fix it.
This is my code:
<?php
class Catalog
{
public function uploadBase64Image()
{
//Base 64 string example
$base64_img = include 'testbase64.php';
$upload_dir = wp_upload_dir();
$upload_path = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir['path']) . DIRECTORY_SEPARATOR;
$title = "test";
$image_parts = explode(";base64,",$base64_img);
$decoded = base64_decode($image_parts[1]);
$mime = substr($base64_img, 11, 4);
$mime = str_replace(';', '', $mime);
$filename = $title . '.' . $mime;
$file_type = 'image/' . $mime;
$hashed_filename = md5($filename . microtime()) . '_' . $filename;
$upload_file = file_put_contents($upload_path . $hashed_filename, $decoded);
$attachment = [
'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);
require_once ABSPATH . 'wp-admin/includes/image.php';
$attach_data = wp_generate_attachment_metadata($attach_id, $upload_dir['path'] . '/' . $hashed_filename);
wp_update_attachment_metadata($attach_id, $attach_data);
return $attach_id;
}
I'm including this class using require_once
in my theme's functions.php
file and using it this way:
function testCatalog()
{
if(!is_admin()) {
$catalog = new Catalog();
return $catalog->uploadBase64Image();
}
}
add_action('init', 'testCatalog');
Any help will be highly appreciated, thanks is advance!
init
hook, which runs any time WordPress is loaded, including AJAX or REST API requests. If you visit a page that sends AJAX requests you're going to get multiple uploads.