WordPress append image dimensions as class names

When inserting images into post or page content WordPress automatically adds three class name to the image tag along with the other attributes, these are the alignment (alignnone), size (size-full) and the attachment id (wp-image-123).

If you need to add additional class names to the defaults without having to manually add them every time you insert a new image, you can make use of either the get_image_tag_class or get_image_tag filters.

The first of the two filters is get_image_tag_class, which allows you to add a value or change the class attribute completely:

function add_image_class($class){
	$class .= ' additional-class';
	return $class;
}
add_filter('get_image_tag_class','add_image_class');

The second function is a little more flexible and provides the ability to alter the image tag completely, thus providing functionality to add the image dimensions to the class names as shown in this example:

function add_image_class_dimensions($html, $id, $alt, $title)
{
	if (preg_match('/width="(\d+)" height="(\d+)"/', $html, $dimensions)) {
		list(,$width, $height) = $dimensions;
		$html = str_replace(
			'class="',
			'class="wp-image-width-'.$width.' wp-image-height-'.$height.' ',
			$html
		);
	}
	return $html;
}
add_filter('get_image_tag', 'add_image_class_dimensions', 10, 4);

In brief, this function matches the dimensions found within the image tag (width and height) and appends them to the front of the class attribute.

Applying both of these filters will output something similar the following code in the TinyMCE editor:

<img class="wp-image-width-200 wp-image-height-100 alignnone size-full wp-image-123" title="Image Title Here" src="/wp-content/uploads/2010/12/my-image.jpg" alt="" width="200" height="100" />

To make use of this functionality you will first need to add the filter and function to your theme’s function.php file. Once this is done, add a new image to your post or page and you will see the custom class names are appended to the image tag. They will not be applied to any existing images within your content, you will have to insert them again from the media library for the changes to be applied.

These are only two examples of what results can be achieved, further adjustments and alterations can be easily added using the two get_image_tag filters.

Leave a Reply