I’m developing a theme which will grab and upload an image when a post is published, using the following function:
media_sideload_img( $url, $id, $description, 'src' );
The problem is, I often update my posts and this ends up with dozens of copies of the same image, which was uploaded several times with every post update.
Is there a way to check whether an attachment exists before uploading it to the server?
P.S: At the moment i’m using this function to get the ID of uploaded attachment:
function get_attachment_id_from_src ($image_src) {
global $wpdb;
$query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
$id = $wpdb->get_var($query);
return $id;
}
Since i have access to the filename that I’m grabbing (from the URL) and they are all unique ( filenames are in hash ), i could check for it’s existence in database but I’m not good enough with SQL queries. If this is an option too, any help is appreciated.
UPDATE
I’m using this query to see if the file exists or not. Is it safe to use this? will it always return the right value?
$wpdb->get_var("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value="$img_name"");