The issue with your code is that the testCatalog function is being called on every page load due to its hook into the init action. Since init runs on every WordPress request (both front-end and admin), your function is uploading the image each time a page is loaded. This is why you see the same image being uploaded multiple times.
To resolve this, you need to modify your approach. Here are a few suggestions:
Limit the Function Call: Instead of hooking into init, consider using a different approach to trigger the image upload. For instance, you might hook into a form submission, a specific admin page load, or a custom action that only occurs under certain conditions.
Add a Check to Prevent Duplicate Uploads: You can add logic to check if the image already exists in the media library before uploading it. This can be done by comparing the file name, or by storing and checking a flag in the database once the image is uploaded for the first time.
Here’s an example of how you might modify your function to include a check for existing images:
class Catalog
{
// ... [rest of your class code]
public function imageExists($hashed_filename) {
$args = array(
'post_type' => 'attachment',
'name' => sanitize_title($hashed_filename),
'posts_per_page' => 1,
'post_status' => 'inherit',
);
$_header = get_posts($args);
return count($_header) > 0;
}
public function uploadBase64Image()
{
// ... [rest of your uploadBase64Image code]
// Check if the image already exists
if ($this->imageExists($hashed_filename)) {
return; // Skip uploading if image exists
}
// ... [rest of your uploadBase64Image code]
}
}
And modify the action hook to a more appropriate trigger:
function testCatalog() {
if (/* your specific condition */) {
$catalog = new Catalog();
return $catalog->uploadBase64Image();
}
}
// Replace 'init' with a more suitable action hook
// add_action('your_custom_action', 'testCatalog');
In the above code, replace /* your specific condition */ with the actual condition that should trigger the upload. For example, it could be a specific page load, a form submission, or a custom admin action. This will prevent the function from running on every page load and only run when your specific condition is met.