Using WordPress ‘intermediate_image_sizes_advanced’ PHP filter

The intermediate_image_sizes_advanced WordPress PHP Filter lets you modify the image sizes that are automatically generated when you upload an image.

Usage

add_filter('intermediate_image_sizes_advanced', 'my_custom_function', 10, 3);

function my_custom_function($new_sizes, $image_meta, $attachment_id) {
    // your custom code here
    return $new_sizes;
}

Parameters

  • $new_sizes (array): Associative array of image sizes to be created.
  • $image_meta (array): The image meta data such as width, height, file, sizes, etc.
  • $attachment_id (int): The attachment post ID for the image.

More information

See WordPress Developer Resources: intermediate_image_sizes_advanced

Examples

Remove default image sizes

Remove all default image sizes when uploading a new image.

add_filter('intermediate_image_sizes_advanced', 'remove_default_image_sizes', 10, 3);

function remove_default_image_sizes($new_sizes) {
    return [];
}

Add a custom image size

Add a custom image size named ‘custom-size’ with dimensions 500×500.

add_filter('intermediate_image_sizes_advanced', 'add_custom_image_size', 10, 3);

function add_custom_image_size($new_sizes) {
    $new_sizes['custom-size'] = array('width' => 500, 'height' => 500, 'crop' => true);
    return $new_sizes;
}

Modify existing image size

Modify the existing ‘medium’ image size dimensions to 400×400.

add_filter('intermediate_image_sizes_advanced', 'modify_existing_image_size', 10, 3);

function modify_existing_image_size($new_sizes) {
    if (isset($new_sizes['medium'])) {
        $new_sizes['medium']['width'] = 400;
        $new_sizes['medium']['height'] = 400;
    }
    return $new_sizes;
}

Conditionally remove image size

Remove the ‘medium’ image size for images larger than 2000×2000.

add_filter('intermediate_image_sizes_advanced', 'conditionally_remove_image_size', 10, 3);

function conditionally_remove_image_size($new_sizes, $image_meta) {
    if ($image_meta['width'] > 2000 && $image_meta['height'] > 2000) {
        unset($new_sizes['medium']);
    }
    return $new_sizes;
}

Add multiple custom image sizes

Add two custom image sizes: ‘custom-small’ (300×300) and ‘custom-large’ (800×800).

add_filter('intermediate_image_sizes_advanced', 'add_multiple_custom_image_sizes', 10, 3);

function add_multiple_custom_image_sizes($new_sizes) {
    $new_sizes['custom-small'] = array('width' => 300, 'height' => 300, 'crop' => true);
    $new_sizes['custom-large'] = array('width' => 800, 'height' => 800, 'crop' => true);
    return $new_sizes;
}