Created
October 23, 2012 00:50
-
-
Save aprakasa/3935970 to your computer and use it in GitHub Desktop.
get attachment ID based on src
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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