Using WordPress ‘has_image_size()’ PHP function

The has_image_size() WordPress PHP function checks if a specific image size exists.

Usage

$check = has_image_size('custom-image-size');
if ($check) {
    echo "Image size exists.";
} else {
    echo "Image size does not exist.";
}

Parameters

  • $name (string) – The image size to check. This function only checks for image sizes that are registered via the add_image_size() function. Core image sizes, namely small, medium, medium_large, and large, are not considered. Hence, checking for a core image size using has_image_size() will always return FALSE.

More information

See WordPress Developer Resources: has_image_size()

Examples

Check if custom image size exists and display message

This code checks if the custom image size ‘my-custom-size’ exists and displays a message accordingly.

$check = has_image_size('my-custom-size');
if ($check) {
    echo "My custom image size exists.";
} else {
    echo "My custom image size does not exist.";
}

Add custom image size if not exists

This code checks if the custom image size ‘new-custom-size’ exists, and if it does not, registers it with the specified dimensions.

if (!has_image_size('new-custom-size')) {
    add_image_size('new-custom-size', 800, 600, true);
}

Remove custom image size if exists

This code checks if the custom image size ‘old-custom-size’ exists and removes it if it does.

if (has_image_size('old-custom-size')) {
    remove_image_size('old-custom-size');
}

Display a list of registered image sizes

This code displays a list of all registered image sizes.

global $_wp_additional_image_sizes;
foreach ($_wp_additional_image_sizes as $size_name => $size_attrs) {
    echo "Image size: {$size_name} - Width: {$size_attrs['width']} - Height: {$size_attrs['height']}<br>";
}

Use with remove_image_size() in a theme’s functions.php file

This code, when added to a theme’s functions.php file, removes the registered image size ‘image-name’ if it exists.

add_action('after_setup_theme', 'remove_registered_image_size');
function remove_registered_image_size() {
    if (has_image_size('image-name')) {
        remove_image_size('image-name');
    }
}

Tagged in

Leave a Comment

Your email address will not be published. Required fields are marked *