Ecommerce Shopify WordPress Discussion

Convert base64 string to WordPress attachment uploads multiple images instead of a single one

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!
Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.