Custom HTML template for images you insert in posts

First of all lets insert an image into a post. Click on «Add Media», choose an image, configure it, click on «Insert into post». And then switch to the «Text» tab in editor.

What I get:

Image html in the post

In this example I selected Link to Mediafile, but if i would like to select Link to none, then the image HTML would be like this:

Image html withoud a link in the post editor

Okay, is there a way to change this default html code?

Do not worry, you do not need to do this operations manually each time. WordPress image_send_to_editor filter will help you to automate it.

Filter: image_send_to_editor

Insert this hook into your theme functions.php file or another one if you know what to do:

function rudr_custom_html_template($html, $id, $caption, $title, $align, $url, $size, $alt) {
	/*
	$html - default HTML, you can use regular expressions to operate with it
	$id - attachment ID
	$caption - image Caption
	$title - image Title
	$align - image Alignment
	$url - link to media file or to the attachment page (depends on what you selected in media uploader)
	$size - image size (Thumbnail, Medium, Large etc)
	$alt - image Alt Text
	*/
 
	/*
	 * First of all lets operate with image sizes
	 */
	list( $img_src, $width, $height ) = image_downsize($id, $size);
	$hwstring = image_hwstring($width, $height);
 
	/*
 	 * Second thing - get the image URL $image_thumb[0]
	 */
	$image_thumb = wp_get_attachment_image_src( $id, $size );
 
	$out = '<div class="rudr-image">'; // I want to wrap image into this div element
	if($url){ // if user wants to print the link with image
		$out .= '<a href="' . $url . '" class="fancybox">';
	}
	$out .= '<img src="'. $image_thumb[0] .'" alt="'.$alt.'" '.$hwstring.'/>';
	if($url){
		$out .= '</a>';
	}
	$out .= '</div>';
	return $out; // the result HTML
}
 
add_filter('image_send_to_editor', 'rudr_custom_html_template', 1, 8);

Let’s look on the result now:

The result of changing default HTML template for image attachments
Misha Rudrastyh

Misha Rudrastyh

I develop websites since 2008, so it is total of 13 years of experience, oh my gosh. Most of all I love love love to create websites with WordPress and Gutenberg, some ideas and thoughts I share throughout my blog.

Need some developer help? Contact me