I am trying to create a plugin that gets data from an external API and stores the data into the database. The data I am receiving, contains Texts and Images. I have to save them separately as in the thumbnail the image doesn't show as it is not saved separated inside the database. The following is my code that I am using.
function save_image_as_attachment($image_url, $post_parent) {
$image_url = esc_url($image_url);
$image_data = wp_remote_retrieve_body(wp_safe_remote_get($image_url));
if ($image_data) {
$file_name = sanitize_file_name(basename($image_url));
$upload_dir = wp_upload_dir();
$upload_path = $upload_dir['path'];
wp_mkdir_p($upload_path);
$file_path = $upload_path . '/' . $file_name;
file_put_contents($file_path, $image_data);
$attachment = array(
'guid' => $upload_dir['url'] . '/' . $file_name,
'post_mime_type' => 'image/jpeg',
'post_title' => $file_name,
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post_parent,
);
$attachment_id = wp_insert_attachment($attachment, $file_path, $post_parent);
if (!is_wp_error($attachment_id)) {
require_once ABSPATH . 'wp-admin/includes/image.php';
$attachment_data = wp_generate_attachment_metadata($attachment_id, $file_path);
wp_update_attachment_metadata($attachment_id, $attachment_data);
return $attachment_id;
}
}
return 0;
}
The following is the error that I am getting.
Warning: file_put_contents(E:\xampp\htdocs\myproject/wp-content/uploads/2023/10/safksdfhkh.jpg): Failed to open stream: No such file or directory in E:\xampp\htdocs\myproject\wp-content\plugins\apiplugin\api_functions.php on line XXX
I have tried using the mkdir($upload_path, 0775);
on if the directory doesn't exist. I have checked that the directory exists and all permissions are proper (755)
. When uploading the image from the WordPress dashboard, the image is uploaded in the database, but I need to store is by getting it from the api.
file_put_contents($file_path, $image_data);
.