Use responsive images (sizes + srcset) with TinyMCE

时间:2017-06-20 12:37:53

标签: javascript tinymce tinymce-4

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).

1 个答案:

答案 0 :(得分:1)

  • 编辑:此答案仅适用于 Wordpress TinyMCE。我没有看到这个问题与 Wordpress 无关。

很老的问题,但我最近遇到了同样的问题。

您可以挂钩 image_send_to_editor 过滤器,仅适用于 TinyMCE。

在这个钩子上,你可以应用到输出,wp_filter_content_tags 函数负责改变一些标记。 目前,它向 srcset HTML 标签添加了 sizesloadingimg 属性。

所以你可以这样使用它:

/**
 * 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 );

此代码可能需要一些额外的验证,但它适用于 Wordpress 5.6