WP get attachment ID from image url

<?php // retrieves the attachment ID from the file URL function pippin_get_image_id($image_url) { global $wpdb; $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); return $attachment[0]; } // set the image url $image_url = 'http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg'; // store the image ID in a var $image_id = pippin_get_image_id($image_url); // retrieve the thumbnail size of our image $image_thumb = wp_get_attachment_image_src($image_id, 'thumbnail'); // display the image echo $image_thumb[0];
Credit: Pippin https://pippinsplugins.com/retrieve-attachment-id-from-image-url/

Note: I am not a fan of direct DB calls to non-index columns but I needed this once and found it short and simple.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.