lifted-l
10/18/2017 - 2:53 PM

Get attachment ID from URL

If you've got the URL for an image, but need the ID to do wp_get_attachment_img and get alt info and whatnot.

// retrieves the attachment ID from the file URL
function ll_get_image_id($image_url) {
  global $wpdb;

  // If testing locally
  $image_url = str_replace('//localhost:3000', site_url(), $image_url);

  $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
  return $attachment[0];
}