Last updated on September 13, 2023

Add Custom Image Size

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

Add a custom image size.

Adding a custom image size in WordPress can be useful if you need to display images in specific sizes that are not already defined in WordPress. This is especially useful when you’re creating a custom plugin or creating a custom child theme. You can add custom image sizes to WordPress using the add_image_size() function. Here’s an example code snippet:

function wpsnippets_add_custom_image_sizes() {
    add_image_size( 'custom-size', 800, 600, true );
}

add_action( 'after_setup_theme', 'wpsnippets_add_custom_image_sizes' );

In this code snippet, we define a function wpsnippets_add_custom_image_sizes that uses the add_image_size function to define a new custom image size called custom-size. The add_image_size function takes three arguments:

  1. $name: The name of the custom image size.
  2. $width: The maximum width of the image in pixels.
  3. $height: The maximum height of the image in pixels.
  4. $crop: Whether to crop the image to the exact dimensions or just resize it proportionally. This argument is optional and defaults to false.

In this example, we add a custom image size in WordPress called ‘custom-size’ with a width of 800 pixels, a height of 600 pixels, and a crop mode of true.

Finally, we use the add_action() function to add the wpsnippets_add_custom_image_sizes() function to the after_setup_theme hook, which is called after the theme is initialized. This ensures that the custom image size is available throughout the site.

Once you have added the custom image size, you can use functions like the the_post_thumbnail function to display the image in the custom size. For example, to display the post thumbnail in the custom-size size, you can use the following code:

if ( has_post_thumbnail() ) {
   the_post_thumbnail( 'custom-size' );
}

This will display the post thumbnail image in the custom-size size, cropped to the exact dimensions specified. You can also use the wp_get_attachment_image_src function to get the URL of the custom image size and use it in your theme or plugin as needed.

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

Leave a Reply

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