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:

Custom HTML template for images you insert in posts

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:

Custom HTML template for images you insert in posts

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

  • What if I use lighbox plugin (fancybox for example) and I want to add «fancybox» class or gallery attribute to the link?
  • What if I need to add a wrapping div to this link?
  • What if I just want to remove default class attribute class="alignnone size-thumbnail wp-image-65"?

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.'/>';
		$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:

Custom HTML template for images you insert in posts