Skip to content

Instantly share code, notes, and snippets.

@zugrina
Last active December 16, 2015 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zugrina/5458979 to your computer and use it in GitHub Desktop.
Save zugrina/5458979 to your computer and use it in GitHub Desktop.
Retrieve Attachment ID from Image URL
<?php
function get_image_id_by_url($image_url) {
global $wpdb;
$prefix = $wpdb->prefix;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM " . $prefix . "posts" . " WHERE guid='%s';", $image_url ));
return $attachment[0];
}
// Usage in theme
$image_id = get_image_id_by_url($image_url);
$image_thumb = wp_get_attachment_image_src($image_id, 'blog-thumb');
echo '<img src="'.$image_thumb[0].'">';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment