Skip to content

Instantly share code, notes, and snippets.

@aprakasa
Created October 23, 2012 00:50
Show Gist options
  • Save aprakasa/3935970 to your computer and use it in GitHub Desktop.
Save aprakasa/3935970 to your computer and use it in GitHub Desktop.
get attachment ID based on src
/**
* This is helper function will get attachment ID based on src
*
* @see http://wordpress.org/support/topic/need-to-get-attachment-id-by-image-url
*/
function get_attachment_id_from_src( $url ) {
global $wpdb;
$id = url_to_postid( $url );
if( $id == 0 ) {
$fileupload_url = get_option( 'fileupload_url', null ).'/';
if ( strpos($url,$fileupload_url)!== false ) {
$url = str_replace( $fileupload_url,'',$url );
$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'", $url ) );
}
}
return $id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment