The image_constrain_size_for_editor() WordPress PHP function scales down the default size of an image to better fit the editor and theme.
Usage
image_constrain_size_for_editor($width, $height, $size = 'medium', $context = null);
Parameters
- $width (int): Width of the image in pixels.
- $height (int): Height of the image in pixels.
- $size (string|int): Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default is ‘medium’.
- $context (string): Could be ‘display’ (like in a theme) or ‘edit’ (like inserting into an editor). Default is null.
More information
See WordPress Developer Resources: image_constrain_size_for_editor()
Examples
Scale down an image to the medium size
This example scales down an image to the medium size for use in a theme.
// Get the image's width and height $width = 800; $height = 600; // Scale down the image list($new_width, $new_height) = image_constrain_size_for_editor($width, $height, 'medium', 'display'); // Output: 300 x 225 echo "Scaled Image: {$new_width} x {$new_height}";
Scale down an image using custom dimensions
This example scales down an image using custom dimensions.
// Get the image's width and height $width = 800; $height = 600; // Custom dimensions $custom_size = array(400, 300); // Scale down the image list($new_width, $new_height) = image_constrain_size_for_editor($width, $height, $custom_size, 'edit'); // Output: 400 x 300 echo "Scaled Image: {$new_width} x {$new_height}";
Scale down an image to the thumbnail size
This example scales down an image to the thumbnail size.
// Get the image's width and height $width = 800; $height = 600; // Scale down the image list($new_width, $new_height) = image_constrain_size_for_editor($width, $height, 'thumbnail', 'edit'); // Output: 150 x 150 echo "Scaled Image: {$new_width} x {$new_height}";
Scale down an image using the medium_large size
This example scales down an image using the medium_large size.
// Get the image's width and height $width = 1200; $height = 900; // Scale down the image list($new_width, $new_height) = image_constrain_size_for_editor($width, $height, 'medium_large', 'edit'); // Output: 768 x 576 echo "Scaled Image: {$new_width} x {$new_height}";
Scale down an image using an unsupported size
This example scales down an image using an unsupported size, which will result in using the content_width size or 500 if that is not set.
// Get the image's width and height $width = 800; $height = 600; // Scale down the image list($new_width, $new_height) = image_constrain_size_for_editor($width, $height, 'unsupported_size', 'edit'); // Output: 500