By default, WordPress creates 3 sizes for every uploaded image (using the default image uploader): thumbnail, medium and large. Since version 2.9, WordPress has added post thumbnail feature that allows us to add more image sizes in order to use them more flexibly in loops, sliders or in other parts of the theme.
In many cases when you want to give user options of image size to show them in some areas such as in a popular widget, related posts area, slides, etc., you're facing the problem of listing all registered image sizes in WordPress. Keep reading the guide below, you'll see this task is easy to complete.
When an image size is registered using add_image_size
function, the size is added to a global variable $_wp_additional_image_sizes
:
$_wp_additional_image_sizes[$name] = array($width, $height, $crop);
So, to list all registered image sizes, the simplest way is looping through $_wp_additional_image_sizes
variable and echo its value. The code below will show all registered image sizes in a select box:
<select name="image_size"> <?php foreach ($_wp_additional_image_sizes as $size_name => $size_attrs): ?> <option value="<?php echo $size_name ?>"><?php echo $size_name ?></option> <?php endforeach; ?> </select>
But dealing with global variable in WordPress isn't a good idea. The reason is that in the future, WordPress may change the variable name, and the code above will break.
To avoid this problem, WordPress has a function get_intermediate_image_sizes
that returns an array of available image sizes. Using this function, our code will be the following:
<?php $image_sizes = get_intermediate_image_sizes(); ?> <select name="image_size"> <?php foreach ($image_sizes as $size_name): ?> <option value="<?php echo $size_name ?>"><?php echo $size_name ?></option> <?php endforeach; ?> </select>
get_intermediate_image_sizes
function that you should know:- If you don't use 'medium' or 'large' sizes (yes, you can deactivate them by setting their dimensions to 0), the function still returns these sizes.
- For 3 default sizes (thumbnail, medium and large), this function doesn't return image size's attributes (width, height, and crop). So be careful to check this before using.
However, as long as you use all default image sizes, this function is safe.
And now you can built more options for your users that let they choose the preferred image sizes for their theme, and I'm sure that will improve your code quality as well as usability.
Leave a Reply