Created
August 16, 2014 12:06
-
-
Save ahmadawais/15e964da8804153f50d4 to your computer and use it in GitHub Desktop.
Get the Attachment ID from an Image URL in WordPress
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
function pn_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+x\d+(?=\.(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; | |
} |
@ahmadawais I gone through this code & it fails to compare at wpostmeta.meta_value = '%s'
It needs to be replaced with wpostmeta.meta_value like '%s'
& variable to be passed like this '%'.$attachment_url.'%'
is it the same as "attachment_url_to_postid" wp function?
https://developer.wordpress.org/reference/functions/attachment_url_to_postid/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Via http://philipnewcomer.net/2012/11/get-the-attachment-id-from-an-image-url-in-wordpress/