functions.php
if( ! function_exists( 'get_attachment_id_from_url' ) ){
function get_attachment_id_from_url( $attachment_url = '' ) {
global $wpdb;
$attachment_id = FALSE;
if ( '' == $attachment_url ) return;
$upload_dir_paths = wp_upload_dir();
if ( FALSE !== strpos( $attachment_url, $upload_dir_paths[ 'baseurl' ] ) ) {
$attachment_url = preg_replace( '/-d+xd+(?=.(jpg|jpeg|png|gif)$)/i', '', $attachment_url );
$attachment_url = str_replace( $upload_dir_paths[ 'baseurl' ] . '/', '', $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;
}
}
No comments yet.