wp_get_attachment_image() not working when trying to add width and height attributes

As written in the documentation, there are no attributes width and height in the fourth parameter of the function. What you might want to do is this:

wp_get_attachment_image(
    $id,
    array( 10, 10 )
);

An alternative and recommended way is to define an image size which will lead WordPress to generate a thumbnail for this size on upload.

add_action( 'after_setup_theme', 'wpse_132171_create_image_size' );
function wpse_132171_create_image_size() {

    add_theme_support( 'post-thumbnails' );
    add_image_size( 'my_size', 10, 10 ); 
}

With that, you can refer to that size by the slug my_size in wp_get_attachment_image():

wp_get_attachment_image( $id, 'my_size' );

For this solution you should rebuild your thumbnails if you have existing images using a plugin like »AJAX Thumbnail Rebuild«

Note: When you use an array as 2nd argument, WordPress will use attachment-{$val1}x{$val2} (a string built from the array values) as class. This behavior breaks as soon as you use the 4th argument (array attributes) and add a custom class key there. The custom class will override what is delivered by core. This could be considered to be a bug.

Leave a Comment