Using WordPress ‘image_downsize’ PHP filter

The image_downsize WordPress PHP Filter allows you to control the output of the image_downsize() function by short-circuiting the downsizing process and returning a custom value instead.

Usage

add_filter( 'image_downsize', 'your_custom_function', 10, 3 );

function your_custom_function( $downsize, $id, $size ) {
    // Your custom code here

    return $downsize;
}

Parameters

  • $downsize (bool|array): Whether to short-circuit the image downsize.
  • $id (int): Attachment ID for the image.
  • $size (string|int[]): Requested image size, can be any registered image size name or an array of width and height values in pixels (in that order).

More information

See WordPress Developer Resources: image_downsize

Examples

Prevent Image Downsizing

Prevent downsizing of images larger than 1200px wide.

add_filter( 'image_downsize', 'prevent_large_image_downsize', 10, 3 );

function prevent_large_image_downsize( $downsize, $id, $size ) {
    $image_data = wp_get_attachment_metadata( $id );
    
    if ( $image_data['width'] > 1200 ) {
        return true;
    }

    return $downsize;
}

Change Image Size

Force all images to be medium size.

add_filter( 'image_downsize', 'force_medium_image_size', 10, 3 );

function force_medium_image_size( $downsize, $id, $size ) {
    return image_downsize( $id, 'medium' );
}

Custom Image Ratio

Keep the image ratio but limit the width to 600px.

add_filter( 'image_downsize', 'custom_image_ratio', 10, 3 );

function custom_image_ratio( $downsize, $id, $size ) {
    $image_data = wp_get_attachment_metadata( $id );
    $ratio = $image_data['height'] / $image_data['width'];
    $new_width = 600;
    $new_height = $new_width * $ratio;

    return array( wp_get_attachment_url( $id ), $new_width, $new_height, false );
}

Add Watermark to Downscaled Images

Apply a watermark to downscaled images.

add_filter( 'image_downsize', 'add_watermark_to_downscaled_images', 10, 3 );

function add_watermark_to_downscaled_images( $downsize, $id, $size ) {
    // Check if it's a downscaled image
    if ( !is_array( $size ) ) {
        return $downsize;
    }

    // Apply watermark function
    $watermarked_image = apply_watermark( $id );

    return $watermarked_image;
}

Disable Image Downsizing for Admins

Disable image downsizing for admin users.

add_filter( 'image_downsize', 'disable_image_downsize_for_admins', 10, 3 );

function disable_image_downsize_for_admins( $downsize, $id, $size ) {
    if ( current_user_can( 'manage_options' ) ) {
        return true;
    }

    return $downsize;
}