Check if image exists before uploading with media_sideload_image()

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"");

2 Answers
2

I wonder if you’re looking for the core attachment_url_to_postid() function that uses:

$sql = $wpdb->prepare(
    "SELECT post_id FROM $wpdb->postmeta 
         WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
    $path
);
$post_id = $wpdb->get_var( $sql );

Note the extra meta key _wp_attached_file check compared to your current snippet.

If you need to check if an image url is an existing thumbnail, then you can check my recent answer here.

Update:

Now I understand it better what you mean. The problem is that _wp_attached_file stores values like 2015/04/test.jpg, if you use year/month uploads, so you could try to search for the test.jpg file with

... WHERE meta_key = '_wp_attached_file' AND meta_value LIKE '%/test.jpg' 

in your custom snippet (watch out for possible SQL injections in your code).

Not sure what your setup is, but another approach might be to store successfully fetched and uploaded images in a more suitable way in the db that suits your needs.

Leave a Comment