How to Change Image Attributes in WordPress Posts

We teamed up with SiteGround
To bring you up to 65% off web hosting, plus free access to the entire SitePoint Premium library (worth $99). Get SiteGround + SitePoint Premium Now

WordPress allows users to place an image into page or post content. Typically, the following HTML code is produced:


<img src="http://www.mysite.com/wp-content/uploads/2011/07/myimage.jpg" 
alt="my image" title="my image title" 
width="100" height="100" class="aligncenter size-full wp-image-123" />

Nothing too horrific, but what if you want to:

  • add your own classes
  • remove the domain from the URL (probably unnecessary unless you’re using RSS feeds)
  • remove the width and height attributes for scaled images in a responsive design?

Fortunately, WordPress provides a couple of filter functions to help you modify the HTML. They can be placed in your theme’s functions.php file or within a plug-in.

important: <img> code is created on insert

Unlike other WordPress content filters, <img> tags are generated when the editor inserts the image into the post. Therefore, these functions will not change code for images which have already been added to a post.

Therefore, the only way to test your code is to repeatedly add and remove images. I recommend switching to WordPress’s HTML view to check the result.

Changing the Image Class

The easiest and most commonly used filter is for the image class:


function image_tag_class($class, $id, $align, $size) {
	return $align;
}
add_filter('get_image_tag_class', 'image_tag_class', 0, 4);

The image_tag_class() function accepts 4 string parameters: the existing class, the image ID (numeric), the alignment (none, left, right, center), and the size (normally ‘full’). It returns a string which will become the <img> tag class. In this example, we’re simply returning the alignment string.

Advanced Image Modification

If we need to make fundamental changes to the <img> tag, we need a filter which can modify the returned HTML directly using string or regular expression replacements, e.g.


function image_tag($html, $id, $alt, $title) {
	return preg_replace(array(
			'/'.str_replace('//','//',get_bloginfo('url')).'/i',
			'/s+width="d+"/i',
			'/s+height="d+"/i',
			'/alt=""/i'
		),
		array(
			'',
			'',
			'',
			'alt="' . $title . '"'
		),
		$html);
}
add_filter('get_image_tag', 'image_tag', 0, 4);

The image_tag() function accepts 4 string parameters: the generated HTML, the image ID (numeric), the alt and title text. In this example, we’ve stripped the domain name from the src URL, removed the height and width attributes and replaced empty alt attributes with the title text. You can change the function accordingly for your own substitutions.

While HTML <img> tag modification is not something you’ll need every day, it’s useful to know that WordPress supports the feature.