I used this cool screenshot from pippinsplugins.com
Add this function to your functions.php file
// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
Then use this code in your page or template to store/print/use the ID:
// set the image url
$image_url = 'http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg';
// store the image ID in a var
$image_id = pippin_get_image_id($image_url);
// print the id
echo $image_id;
Update: Since wp 4.0.0 there is a new function that does the job. I haven't tested it yet, but it goes something like this:
https://developer.wordpress.org/reference/functions/attachment_url_to_postid/
Old answer: The best solution I've found so far is the following:
https://frankiejarrett.com /2013/05/get-an-attachment-id-by-url-in-wordpress/
I think this is the best for two reasons:
I used this cool screenshot from pippinsplugins.com
Add this function to your functions.php file
Then use this code in your page or template to store/print/use the ID:
Original post here: https://pippinsplugins.com/retrieve-attachment-id-from-imageurl/
Hope it helps ;) Francis