The following is my code I am using to store image that I am getting from an external API using my own plugin. The images, or any media in general, are not loading on the frontend or the Media tab on the WordPress Dashboard.
function save_media_as_attachment($media_url, $post_id) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
if (empty($media_url)) {
return false;
}
$temp_file = download_url($media_url);
if (is_wp_error($temp_file)) {
return false;
}
$file_name = basename($media_url);
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
$post_mime_type = 'image/jpeg'; // Default to JPEG
if (strtolower($file_extension) === 'jpg' || strtolower($file_extension) === 'jpeg') {
$post_mime_type = 'image/jpeg';
} elseif (strtolower($file_extension) === 'png') {
$post_mime_type = 'image/png';
} elseif (strtolower($file_extension) === 'mp4') {
$post_mime_type = 'video/mp4';
}
$attachment = array(
'post_title' => sanitize_file_name($file_name),
'post_content' => '',
'post_status' => 'inherit',
'post_mime_type' => $post_mime_type,
);
$attachment_id = wp_insert_attachment($attachment, $temp_file, $post_id);
if (!is_wp_error($attachment_id)) {
$attachment_data = wp_generate_attachment_metadata($attachment_id, $temp_file);
wp_update_attachment_metadata($attachment_id, $attachment_data);
update_post_meta($attachment_id, '_wp_attached_file', $file_name);
@unlink($temp_file);
return $attachment_id;
}
@unlink($temp_file);
return false;
}
After doing some research I tried the following
- Regenerating the images by adding the following code inside my theme's
function.php
file
function regenerate_all_image_sizes() {
$args = array(
'post_type' => 'attachment',
'post_status' => 'any',
'posts_per_page' => -1,
);
$attachments = new WP_Query($args);
if ($attachments->have_posts()) {
while ($attachments->have_posts()) {
$attachments->the_post();
$attachment_id = get_the_ID();
wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, get_attached_file($attachment_id)));
}
}
wp_reset_postdata();
}
regenerate_all_image_sizes();
Which did nothing.
- Checking file permissions
- Double checking Image MIME Type
- Checking file integrity and not corrupted when downloaded using URL on my machine
- Also tried disabling
Options -Indexes
from the .htaccess
The above didn't solve the problem as to why the images are not loading.
unlnk $temp_file
and that did nothing either. So I believewp_insert_attachment
is not working.