function insert_attachment_from_url($image_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';
// Get the original image name from the URL
$image_name = basename($image_url);
// Decode URL-encoded characters in the filename
$image_name = urldecode($image_name);
// Create a sanitized filename for WordPress
$sanitized_name = sanitize_file_name($image_name);
$upload_dir = wp_upload_dir();
// Handle URL encoding in the image URL
$encoded_url = str_replace(' ', '%20', $image_url);
// Get the image data
$image_data = file_get_contents($encoded_url);
if (!$image_data) {
return false;
}
$file_path = $upload_dir['path'] . '/' . $sanitized_name;
file_put_contents($file_path, $image_data);
$file_type = wp_check_filetype($file_path);
$attachment = array(
'post_mime_type' => $file_type['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $image_name), // Remove file extension for title
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment($attachment, $file_path, $post_id);
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);
return $attach_id;
}