Since wordpress version 4.0 there is a wordpress core function attachment_url_to_postid that "Tries to convert an attachment URL into a post ID." But these function has huge flaw cos it can't convert custom image url sizes.
Almost all top answers before trying solve these problem, but all of them have a very heavy database query trying to get all existing attachments and then loop through all of them trying to get attachment metadata and find custom sizes in it. It works well only if you have small amount of attachments in your wordpress project. But you definitely will get performance problem if you have big project with 10000 + attachments.
But you can extend attachment_url_to_postid core function through existing filter attachment_url_to_postid then trying to force attachment_url_to_postid function search among custom image sizes too.
Just add code below to functions.php file of your active wordpress theme.
add_filter( 'attachment_url_to_postid', 'change_attachment_url_to_postid', 10, 2 );
function change_attachment_url_to_postid( $post_id, $url ) {
if ( ! $post_id ) {
$file = basename( $url );
$query = array(
'post_type' => 'attachment',
'fields' => 'ids',
'meta_query' => array(
array(
'key' => '_wp_attachment_metadata',
'value' => $file,
'compare' => 'LIKE',
),
)
);
$ids = get_posts( $query );
if ( ! empty( $ids ) ) {
foreach ( $ids as $id ) {
$meta = wp_get_attachment_metadata( $id );
foreach ( $meta['sizes'] as $size => $values ) {
$image_src = wp_get_attachment_image_src( $id, $size );
if ( $values['file'] === $file && $url === array_shift( $image_src ) ) {
$post_id = $id;
}
}
}
}
}
return $post_id;
}