
HTML Template to Insert Images in Posts

Photo by Nicklbaert on Unsplash
Images are one of the elements that can make an article more interesting and also serve the purpose of providing illustrations or representations of the content within an article.
This time, Mangcoding will share an HTML template to insert images into posts, especially in WordPress. Without further ado, let’s dive into the article!
Step 1: Insert an image into the post. Click “Add Media,” select the image, configure it, then click “Insert into Post.” Afterward, switch to the “Text” tab in the editor.
Here’s an example below:
In the example above, I selected “Link to Mediafile,” but if I had chosen “Link to None,” the HTML for the image would look like this:
Now, some of you might have questions—can we change this default HTML code?
- What if I’m using a lightbox plugin (like Fancybox) and want to add the class “fancybox” or gallery attributes to the link?
- What if I need to add a wrapper div around the link?
- What if I just want to remove the default class attribute
- class=”alignnone size-thumbnail wp-image-65″?
Don’t worry! You don’t need to manually do this every time. The WordPress image_send_to_editor filter can help automate this process.
Please add the following code to the `functions.php` file in your theme:
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);
The result will look like this:
That’s the article Mangcoding shared. Hopefully, this article is useful and provides new knowledge for you. If you have any constructive criticism or suggestions, feel free to comment or send them via Email or Mangcoding’s social media.
Source: Rudrastyh.com