The image_resize_dimensions WordPress PHP Filter allows you to override the default behavior of WordPress when resizing image assets, including thumbnail cropping.
Usage
add_filter('image_resize_dimensions', 'your_custom_function', 10, 6);
function your_custom_function($null, $orig_w, $orig_h, $dest_w, $dest_h, $crop) {
// your custom code here
return $null;
}
Parameters
$nullnull|mixed – Whether to preempt output of the resize dimensions.$orig_wint – Original width in pixels.$orig_hint – Original height in pixels.$dest_wint – New width in pixels.$dest_hint – New height in pixels.$cropbool|array – Whether to crop the image to specified width and height or resize. An array can specify the positioning of the crop area. Default false.
More information
See WordPress Developer Resources: image_resize_dimensions
Examples
Custom crop positions
Override the default crop position to be centered horizontally and aligned to the top.
add_filter('image_resize_dimensions', 'custom_crop_position', 10, 6);
function custom_crop_position($null, $orig_w, $orig_h, $dest_w, $dest_h, $crop) {
if (!$crop) {
return $null;
}
$crop_x = round(($orig_w - $dest_w) / 2);
$crop_y = 0;
return array(0, 0, $crop_x, $crop_y, $dest_w, $dest_h, $dest_w, $dest_h);
}
Disable cropping
Prevent image cropping when resizing.
add_filter('image_resize_dimensions', 'disable_image_cropping', 10, 6);
function disable_image_cropping($null, $orig_w, $orig_h, $dest_w, $dest_h, $crop) {
if ($crop) {
$crop = false;
}
return $null;
}
Custom aspect ratio
Maintain a custom aspect ratio when resizing images.
add_filter('image_resize_dimensions', 'custom_aspect_ratio', 10, 6);
function custom_aspect_ratio($null, $orig_w, $orig_h, $dest_w, $dest_h, $crop) {
$aspect_ratio = 16 / 9;
$new_height = round($dest_w / $aspect_ratio);
return array(0, 0, 0, 0, $dest_w, $new_height, $orig_w, $orig_h);
}
Prevent resizing for small images
Disable resizing for images smaller than the desired dimensions.
add_filter('image_resize_dimensions', 'prevent_small_image_resize', 10, 6);
function prevent_small_image_resize($null, $orig_w, $orig_h, $dest_w, $dest_h, $crop) {
if ($orig_w < $dest_w && $orig_h < $dest_h) {
return false;
}
return $null;
}
Add a custom resizing method
Create a custom resizing method for images with a specific aspect ratio.
add_filter('image_resize_dimensions', 'custom_resizing_method', 10, 6);
function custom_resizing_method($null, $orig_w, $orig_h, $dest_w, $dest_h, $crop) {
$aspect_ratio = $orig_w / $orig_h;
if ($aspect_ratio == 2){
// Perform custom resizing for images with an aspect ratio of 2
$new_width = $dest_w;
$new_height = round($new_width / 2);
$crop_x = round(($orig_w - $new_width) / 2);
$crop_y = round(($orig_h - $new_height) / 2);
return array(0, 0, $crop_x, $crop_y, $new_width, $new_height, $new_width, $new_height);
}
// For other aspect ratios, use the default behavior
return $null;
}