Using WordPress ‘image_downsize()’ PHP function

The image_downsize() WordPress PHP function scales an image to fit a particular size, such as ‘thumb’ or ‘medium’.

Usage

image_downsize( $id, $size );

Example:

$image_url = image_downsize( 123, 'medium' );

Parameters

  • $id (int) – Required. Attachment ID for the image.
  • $size (string|int) – Optional. Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default ‘medium’.

More information

See WordPress Developer Resources: image_downsize

Examples

Get thumbnail-sized image URL

Get the thumbnail-sized image URL for an attachment with an ID of 123.

$thumbnail_url = image_downsize( 123, 'thumbnail' );

Get custom-sized image URL

Get the custom-sized image URL (200×200) for an attachment with an ID of 123.

$custom_size_url = image_downsize( 123, array( 200, 200 ) );

Create a function to get medium-sized image URL

Create a function to get the medium-sized image URL for an attachment.

function wp_get_attachment_medium_url( $id ) {
    $medium_array = image_downsize( $id, 'medium' );
    $medium_path = $medium_array[0];
    return $medium_path;
}

$medium_url = wp_get_attachment_medium_url( 123 );

Display an image with a custom size in a post

Display an image with a custom size (150×150) in a post.

$post_thumbnail_id = get_post_thumbnail_id( $post_id );
$image_src = image_downsize( $post_thumbnail_id, array( 150, 150 ) );
echo '<img src="' . $image_src[0] . '" width="' . $image_src[1] . '" height="' . $image_src[2] . '">';

Get image URL for the registered custom image size

Get the image URL for a registered custom image size called ‘custom-size’.

add_image_size( 'custom-size', 300, 300, true );
$custom_size_url = image_downsize( 123, 'custom-size' );