Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use responsive images (sizes + srcset) with TinyMCE

I want to change the img-tags generated by TinyMCE to responsive ditto when uploading an image, something like this (using lazysizes):

<img
    data-sizes="auto"
    data-src="image2.jpg"
    data-srcset="image1.jpg 300w,
                 image2.jpg 600w,
                 image3.jpg 900w"
    class="lazyload" />

In the deprecated (and not useful, to me) MCImageManager you could do this:

imagemanager_insert_template : '<img src="{$url}" />'

Is there something similar in TinyMCE? Either in the core or some of the (free) plugins? I have full control over the back end where I upload the images and I am already doing the resizing there (using ImageSharp).

like image 247
Oskar Avatar asked Jun 20 '17 12:06

Oskar


1 Answers

  • Edit: This answer works for Wordpress TinyMCE only. I didn't see that the question was not related with Wordpress.

Very old question, but I got the same problem recently.

You can hook image_send_to_editor filter, that is only apply to TinyMCE.

On this hook, you can apply to the output, the wp_filter_content_tags function that is responsible for change some markup. Currently it adds srcset, sizes, and loading attributes to img HTML tags.

So you can use it like this:

/**
 * Change the image markup to include srcset and sizes
 * when using tinyMCE editor
 *
 * @param $html
 * @param $id
 * @param $alt
 * @param $title
 * @param $align
 * @param $url
 * @param $size
 * @return string
 * @throws Exception
 */
function storms_img_markup( $html, $id, $caption, $title, $align, $url, $size, $alt, $rel ) {
    return wp_filter_content_tags( $html );
}
add_filter( 'image_send_to_editor', 'storms_img_markup', 10, 9 );

This code may require some additional validation, but it works on Wordpress 5.6

like image 180
Vinicius Garcia Avatar answered Nov 10 '22 10:11

Vinicius Garcia