set_post_thumbnail or media_sideload_image adds image multiple times in media library

<?php $post_id = get_queried_object_id(); $bla = “myImageURL”; // Set the image URL $image_url = $bla; // Check if the image already exists in the media library $existing_image = get_posts(array( ‘post_type’ => ‘attachment’, ‘meta_key’ => ‘_wp_attached_file’, ‘meta_value’ => sanitize_file_name(basename($image_url)) )); if (!$existing_image) { // Image does not exist in the media library, so download it $image_id … Read more

How to overwrite image if it already exists – WordPress, Gravity form

These lines of code and can help you to overwrite image $attachment_id = get_post_thumbnail_id($post_id); wp_delete_attachment($attachment_id, true); if(isset($file) && !empty($file) ){ $upload_overrides = array(‘test_form’=> false); $movefile = wp_handle_upload($file, $upload_overrides); $filename = basename( $movefile[‘url’] ); $wp_filetype = wp_check_filetype($filename, null ); $attachment = array( ‘guid’ => $wp_upload_dir[‘url’] . “https://wordpress.stackexchange.com/” . $filename, ‘post_mime_type’ => $wp_filetype[‘type’], ‘post_title’ => preg_replace(‘/\.[^.]+$/’, ”, … Read more