How to change the markup Wordpress inserts for post images
Question
I am developing a theme with Underscores for WordPress.
When the user adds an image using the TinyMCE editor the following code is inserted:
<img class="wp-image-45 size-full aligncenter" src="http://example.com/wp-content/uploads/2016/06/process.png" alt="process" width="849" height="91" />
When I look at the final page generated by Wordpress, the HTML appears in the DOM
<img class="wp-image-45 size-full aligncenter" src="http://example.com/wp-content/uploads/2016/06/process.png" alt="process" width="849" height="91" srcset="http://example.com/wp-content/uploads/2016/06/process.png 849w, http://example.com/wp-content/uploads/2016/06/process-300x32.png 300w, http://example.com/wp-content/uploads/2016/06/process-768x82.png 768w" sizes="(max-width: 849px) 100vw, 849px">
I have created a function to generate a thumbnail with a width of 300px:
add_action( 'after_setup_theme', 'images_theme_setup' );
function images_theme_setup() {
add_image_size( 'preload-thumb', 300 ); // 300 pixels wide (and unlimited height)
}
Now I want to use Pil (https://github.com/gilbitron/Pil) compatible markup to serve images so I can serve the preload-thumb
and then serve the larger image
I need to change to the markup to match this below
<figure class="pil">
<img src="img/my-image.jpg" data-pil-thumb-url="img/thumb-my-image.jpg" data-full-width="5616" data-full-height="3744" alt="">
</figure>
Solution
As far as I know you could hook into the filter image_send_to_editor
like this:
function html5_insert_image($html, $id, $caption, $title, $align, $url) {
$url = wp_get_attachment_url($id);
$html5 = "<figure id='post-$id media-$id' class='align-$align'>";
$html5 .= "<img src='$url' alt='$title' />";
$html5 .= "</figure>";
return $html5;
}
add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );
For additional tags like data-pil-thumb-url
and data-full-width
and data-full-height
you could add the appropriate code inside that function and add them to the $html5
string.
See also this page for an example featuring a caption <figcaption>
at css-tricks or check this more detailed 'walk through'.
OTHER TIPS
There's a filter called image_send_to_editor
that lets you specify the markup. You will also need wp_get_attachment_metadata
to retrieve width and height. It is called like this (untested):
add_filter( 'image_send_to_editor', 'wpse_231693_img_markup', 10, 7 );
function wpse_231693_img_markup ($html, $id, $alt, $title, $align, $url, $size ) {
$metadata = wp_get_attachment_metadata ($id);
$url = wp_get_attachment_url($id);
$html = '<figure class="pil"><img src="' . $url .
'" data-pil-thumb-url="XXX" data-full-width="' . $metadata['width'] .
'" data-full-height="' . $metadata['height'] .
'" alt="' . $alt . '"></figure>';
return $html;
}
You will need some clever regex to construct XXX from $url, but I'll leave that to you.