wordpress image size based on url

I’m using a custom field to select an image’s url.

My client is inserting and uploading all the image so this needs to be really simple. Thats why I’m trying to handle it behind the scene.

Read More

The problem I’ve run into is all I have in the url of the full size image which is really slowing down load time.

Is there a way I can insert a thumbnail or other image size based on the full size url?

I’ve tried this which sort of works but the problem I’m having is some images don’t have the same dentition, so this needs to be done more dynamical.

<? $reduceimage = str_replace('.jpg', '-330x220.jpg' , $defaultimage); ?>

Related posts

Leave a Reply

1 comment

  1. I think it’s best to rely on wordpress’ native wp_get_attachment_image_src() function to get different sizes of image. But to do so, you need attachment ID, not the url.
    The function to convert the url to ID:

    function fjarrett_get_attachment_id_by_url( $url ) {
    
        // Split the $url into two parts with the wp-content directory as the separator
        $parsed_url  = explode( parse_url( WP_CONTENT_URL, PHP_URL_PATH ), $url );
    
        // Get the host of the current site and the host of the $url, ignoring www
        $this_host = str_ireplace( 'www.', '', parse_url( home_url(), PHP_URL_HOST ) );
        $file_host = str_ireplace( 'www.', '', parse_url( $url, PHP_URL_HOST ) );
    
        // Return nothing if there aren't any $url parts or if the current host and $url host do not match
        if ( ! isset( $parsed_url[1] ) || empty( $parsed_url[1] ) || ( $this_host != $file_host ) ) {
            return;
        }
    
        // Now we're going to quickly search the DB for any attachment GUID with a partial path match
    
        // Example: /uploads/2013/05/test-image.jpg
        global $wpdb;
        $attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->prefix}posts WHERE guid RLIKE %s;", $parsed_url[1] ) );
    
        // Returns null if no attachment is found
        return $attachment[0];
    }
    

    Thanks to Frankie Jarrett.

    Then you can get other sizes easily:

    $medium_image = wp_get_attachment_image_src( fjarrett_get_attachment_id_by_url($image_link), 'medium');
    

    If you need link from this image:

    $medium_image_link = $medium_image[0];
    $html = '<img src="'.$medium_image_link.'" alt="" />';