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.