gdbakery
Forum Replies Created
Viewing 1 replies (of 1 total)
-
Forum: Developing with WordPress
In reply to: Avoid uploading duplicates with media_sideload_imageCertainly! To avoid uploading duplicate images to the WordPress media gallery, you can use the
media_handle_sideloadfunction along with a check to see if the image already exists in the media library. Here’s a sample code snippet that demonstrates this:phpCopy code
function upload_and_attach_image($image_url, $post_id) { // Check if the image URL already exists in the media library $existing_attachment = get_attachment_id_from_url($image_url); if ($existing_attachment) { // If the image already exists, return the existing attachment ID return $existing_attachment; } // If the image doesn't exist, sideload and attach it $attachment_id = media_handle_sideload(array('file' => $image_url, 'post_id' => $post_id)); if (!is_wp_error($attachment_id)) { // Attachment successful, return the new attachment ID return $attachment_id; } else { // Handle error if any error_log('Error uploading image: ' . $attachment_id->get_error_message()); return false; } } function get_attachment_id_from_url($image_url) { // Search for an existing attachment based on the image URL global $wpdb; $attachment_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url)); return $attachment_id; } // Example usage $image_url = 'https://example.com/image.jpg'; $post_id = 123; // Replace with the ID of your post $attachment_id = upload_and_attach_image($image_url, $post_id); if ($attachment_id) { // Use $attachment_id as needed (e.g., set as the post thumbnail) set_post_thumbnail($post_id, $attachment_id); }This code checks if the image already exists in the media library based on its URL before attempting to upload it again. If the image is already in the media library, it retrieves the existing attachment ID, avoiding duplicates. Otherwise, it proceeds to sideload and attach the image.
- This reply was modified 2 years, 5 months ago by bcworkz. Reason: code format partially fixed
Viewing 1 replies (of 1 total)