WordPress has a function solely designed for this purpose. the attachment_url_to_postid()
allows you to retrieve an attachment’s ID from it’s URL, which then you can use to get the post’s ID later.
If you want to do it by writing a MySQL query, i would however prefer to suggest searching the file’s name in meta_value
instead:
$basename = basename ($image_url);
$sql = "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value="$basename "";
$id = $wpdb->get_var($sql);
GUID columns are hardcoded in database once you publish a post. So, if you publish a post on localhost, a sample GUID will be like this:
http://localhost/wp-content/uploads/my-image.jpg
But you will be searching for an online URL of your image by using this:
$wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
Which will return nothing, obviously. However you can use LIKE
in conjunction with basename:
$img_name = basename ($image_url);
$wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid LIKE '%s';", $img_name ));
Which is kind of the same as the first approach.