I have a similar need in some projects of mine and solved by getting the image ID from it’s URL and then writing the markup with wp_get_attachment_image
as it will return a markup with srcset attribute.
To get the image ID, I am using Gustavo Bordoni’s helpers as it follows and shown in here.
function attachment_url_to_postid( $url ) {
global $wpdb;
$dir = wp_upload_dir();
$path = $url;
if ( 0 === strpos( $path, $dir['baseurl'] . "https://wordpress.stackexchange.com/" ) ) {
$path = substr( $path, strlen( $dir['baseurl'] . "https://wordpress.stackexchange.com/" ) );
}
$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 );
if ( ! empty( $post_id ) ) {
return (int) $post_id;
}
}
function attachment_url_to_postid( $url ) {
global $wpdb;
$dir = wp_upload_dir();
$path = $url;
if ( 0 === strpos( $path, $dir['baseurl'] . "https://wordpress.stackexchange.com/" ) ) {
$path = substr( $path, strlen( $dir['baseurl'] . "https://wordpress.stackexchange.com/" ) );
}
$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 );
if ( ! empty( $post_id ) ) {
return (int) $post_id;
}
}
and it’s wrapper:
function get_attachment_id_by_url( $url ) {
$post_id = attachment_url_to_postid( $url );
if ( ! $post_id ){
$dir = wp_upload_dir();
$path = $url;
if ( 0 === strpos( $path, $dir['baseurl'] . "https://wordpress.stackexchange.com/" ) ) {
$path = substr( $path, strlen( $dir['baseurl'] . "https://wordpress.stackexchange.com/" ) );
}
if ( preg_match( '/^(.*)(\-\d*x\d*)(\.\w{1,})/i', $path, $matches ) ){
$url = $dir['baseurl'] . "https://wordpress.stackexchange.com/" . $matches[1] . $matches[3];
$post_id = attachment_url_to_postid( $url );
}
}
return (int) $post_id;
}
and then, the markup:
wp_get_attachment_image( $image_id, $args['desired_image_size_as_registered'] );
Hope it helps.