0

Get the Attachment ID from an Image URL in WordPress

I recently needed a way to get the ID of a WordPress image attachment, but I only had the image URL to work with. The problem was complicated by the fact that the image URL could be a thumbnail of the original image attachment, i.e. one of the auto-generated post thumbnail image sizes.

There’s no built-in function in WordPress for doing this, and a Google search provided only partial solutions. Some of those functions queried attachment GUIDs, but that method isn’t always reliable. Other solutions didn’t work with thumbnail images. However, by combining several of these partial solutions, I put together this function which works well for my purposes:

[code language=”css”]
function sp_get_attachment_id_from_url( $attachment_url = ” ) {

global $wpdb;
$attachment_id = false;

// If there is no url, return.
if ( ” == $attachment_url )
return;

// Get the upload directory paths
$upload_dir_paths = wp_upload_dir();

// Make sure the upload path base directory exists in the attachment URL, to verify that we’re working with a media library image
if ( false !== strpos( $attachment_url, $upload_dir_paths[‘baseurl’] ) ) {

// If this is the URL of an auto-generated thumbnail, get the URL of the original image
$attachment_url = preg_replace( ‘/-d+xd+(?=.(jpg|jpeg|png|gif)$)/i’, ”, $attachment_url );

// Remove the upload path base directory from the attachment URL
$attachment_url = str_replace( $upload_dir_paths[‘baseurl’] . ‘/’, ”, $attachment_url );

// Finally, run a custom database query to get the attachment ID from the modified attachment URL
$attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = ‘_wp_attached_file’ AND wpostmeta.meta_value = ‘%s’ AND wposts.post_type = ‘attachment’", $attachment_url ) );

}

return $attachment_id;
}
[/code]

[code]
$attch_id = sp_get_attachment_id_from_url(get_post_meta($page_for_posts, ‘wpcf-header-image’, true));
$image_attributes = wp_get_attachment_image_src( $attch_id, ‘thumbnail’ ); // returns an array

print_r($image_attributes);
[/code]

I post it here in the hopes that it may be useful to other developers who are struggling with this same problem, and also as a reference for myself in the future.

If you see a way that this function can be improved, please comment.

Sandeep Kumar

Sandeep kumar is a web developer and a professinal blogger. He works for latest technologies and write articles what he learn. In ICodeHub he share web languages tutorials and other programming tips and tricks. if you need some help or have some suggestion then mail him at sandeep92pal@gmail.com without any hesitation. He believes in learning and sharing.