Use add_image_size() to make WordPress generate extra image sizes every time an image is uploaded. This gives you exact dimensions for cards, banners and galleries.

Register the sizes

function lotgrafix_image_sizes() {
    add_image_size( 'lotgrafix-card', 600, 400, true );
    add_image_size( 'lotgrafix-banner', 1400, 500, array( 'center', 'top' ) );
    add_image_size( 'lotgrafix-tall', 400, 0 );
}
add_action( 'after_setup_theme', 'lotgrafix_image_sizes' );

How the arguments work

  • The first value is the size name.
  • Then the width and the height in pixels. A height of 0 means the height is calculated automatically.
  • true crops the image to the exact size. false resizes it to fit inside the box.
  • An array like array( 'center', 'top' ) sets the crop position.

Use the size in a template

the_post_thumbnail( 'lotgrafix-card' );

Make the sizes available in the editor

By default custom sizes do not show in the image size dropdown of the block editor.

function lotgrafix_image_size_names( $sizes ) {
    return array_merge( $sizes, array(
        'lotgrafix-card'   => __( 'Lotgrafix Card', 'lotgrafix' ),
        'lotgrafix-banner' => __( 'Lotgrafix Banner', 'lotgrafix' ),
    ) );
}
add_filter( 'image_size_names_choose', 'lotgrafix_image_size_names' );

Important notes

  • New sizes only apply to images uploaded after you add them. Regenerate older images with a plugin such as Regenerate Thumbnails or with WP-CLI using wp media regenerate.
  • If the original image is smaller than the size, WordPress will not create that size.
  • Do not register too many sizes. Each one creates a new file for every upload.
«
»