What I'm wanting to do is this:

  • From a remote image url provided, I want to generate a thumbnail with specific dimensions.
  • Save the generated image thumbnail file only, not the original remote image
  • Save the image thumbnail file in a custom directory (not inside /wp-content/media/)

I'm not sure how to proceed, I'm currently reading guides online and having my eye on wp_get_image_editor() though I'm not really sure if I'm on the right track.

1 Answer 1


I managed to find a solution to my problem, though I ended up using PHP GD functions instead of using a wordpress function. I hope this can help others who are trying to do something similar.

$src    = // Source image URL
$max_w  = // Output maximum width
$max_h  = // Output maximum height
$dir    = // Output directory
$fle    = // Output filename

function createThumbnail( $src, $max_w, $max_h, $dir, $fle ) {
    $img_url = file_get_contents( $src );
    $img = imagecreatefromstring( $img_url );
    $old_x = imagesx( $img );   // Source image width
    $old_y = imagesy( $img );   // Source image height

    // Conditions for maintaining output aspect ratio
    switch ( true ) {
        case ( $old_x > $old_y ):   // If source image is in landscape orientation
            $thumb_w = $max_w;
            $thumb_h = $old_y / $old_x * $max_w;
        case ( $old_x < $old_y ):   // If source image is in portrait orientation
            $thumb_w  = $old_x / $old_y * $max_h;
            $thumb_h  = $max_h;
        case ( $old_x == $old_y ):  // If source image is a square
            $thumb_w = $max_w;
            $thumb_h = $max_h;

    $thumb = imagecreatetruecolor( $thumb_w, $thumb_h );

    I quoted this one out since I ran in compatibility issues, I'm using PHP 5.3.x
    and imagesetinterpolation() doesn't exist in this version

    imagesetinterpolation( $thumb, IMG_SINC ); // Recommended Downsizing Algorithm

    imagecopyresampled( $thumb, $img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y );

    $result = imagejpeg( $thumb, $dir . $fle );

    imagedestroy( $thumb ); 
    imagedestroy( $img );

    return $result;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.