false]; // allows frontend upload
$file = $_FILES[‘image_file’];
$uploaded_file = wp_handle_upload($file, $upload_overrides);
if (isset($uploaded_file[‘file’])) {
$file_path = $uploaded_file[‘file’];
$file_url = $uploaded_file[‘url’];
$file_type = wp_check_filetype($file_path, null);
$attachment = [
‘post_mime_type’ => $file_type[‘type’],
‘post_title’ => sanitize_file_name(basename($file_path)),
‘post_content’ => ”,
‘post_status’ => ‘inherit’,
];
$attach_id = wp_insert_attachment($attachment, $file_path);
require_once(ABSPATH . ‘wp-admin/includes/image.php’);
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);
echo ‘
Image uploaded successfully! You can now find it in the Media Library.
‘;
} else {
echo ‘
Upload failed: ‘ . $uploaded_file[‘error’] . ‘
‘;
}
} else {
echo ‘
Security check failed!
‘;
}
}
?>