Recently, I worked with an image uploader script which transform a native text field into an image uploader. The script works really well.

However, the uploader will only return the URL of the full image size, not the image object or attachment id. The problem with this is there is no way to choose which image size to return.

From there, I got an idea to why not get the image ID from the returned URL. I found this script which get the image ID from the database using the full image URL which is perfect for what I need.

function ywt_image_id_from_url($image_url) {
        global $wpdb;

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

Using the script, I can get the image ID and use it with wp_get_attachment_image_src($attachment_id_ID, $size) to get the desired image size.

Example Usage

$attachment_id = bodypress_image_id_from_url( $image_url );
$thumbnail = wp_get_attachment_image_src($attachment_id, 'thumbnail') ;

echo '<img src="' . $thumbnail . '">';