Last updated on September 13, 2023

Custom Image Size

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Modify the default image sizes and add custom sizes.

By default, WordPress generates several image sizes every time you upload an image to your site. However, you may want to change the default image sizes to better fit your specific needs. Here’s an example code snippet that demonstrates how to change the default WordPress image sizes:

function wpsnippets_custom_image_sizes() {
    update_option( 'thumbnail_size_w', 400 );
    update_option( 'thumbnail_size_h', 400 );
    update_option( 'medium_size_w', 800 );
    update_option( 'medium_size_h', 800 );
    update_option( 'large_size_w', 1200 );
    update_option( 'large_size_h', 1200 );
}

add_action( 'after_setup_theme', 'wpsnippets_custom_image_sizes' );

In the code snippet above, we define a function called wpsnippets_custom_image_sizes that uses the update_option function to set new values for the width and height of the default WordPress image sizes. In this example, we set the thumbnail size to 400×400 pixels, the medium size to 800×800 pixels, and the large size to 1200×1200 pixels.

We then hook this function to the after_setup_theme action using the add_action function. This ensures that the function is executed after the theme has been initialized, allowing us to modify the default image sizes.

Once you have added this code snippet, WordPress will generate images in the new sizes you specified whenever you upload a new image. If you have already uploaded images to your site, you may need to regenerate them to take advantage of the new image sizes. You can use a plugin like Regenerate Thumbnails to regenerate your images.

Last updated on September 13, 2023. Originally posted on May 3, 2023.

Leave a Reply