最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp kses - How to allow data:image attribute in src tag during post insert?

programmeradmin3浏览0评论

I'm inserting a post using wp_post_insert(). And my post's content looks like this:

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAN4AAAB6CA { ... }

but on the insert process, Wordpress removes the data attribute. So above code becomes this:

 <img src="image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAN4AAAB6CA { ... }

I've tried something like this but no luck:

function my_filter_allowed_html($allowed, $context){
if (is_array($context)) {
    return $allowed;
}

if ($context === 'post') {
    $allowed['img']['data'] = true;
    $allowed['src']['data'] = true;

}

return $allowed;
}
add_filter('wp_kses_allowed_html', 'my_filter_allowed_html', 10, 2);

How can I avoid this?

I'm inserting a post using wp_post_insert(). And my post's content looks like this:

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAN4AAAB6CA { ... }

but on the insert process, Wordpress removes the data attribute. So above code becomes this:

 <img src="image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAN4AAAB6CA { ... }

I've tried something like this but no luck:

function my_filter_allowed_html($allowed, $context){
if (is_array($context)) {
    return $allowed;
}

if ($context === 'post') {
    $allowed['img']['data'] = true;
    $allowed['src']['data'] = true;

}

return $allowed;
}
add_filter('wp_kses_allowed_html', 'my_filter_allowed_html', 10, 2);

How can I avoid this?

Share Improve this question edited Nov 29, 2019 at 12:06 Earth asked Nov 28, 2019 at 15:35 EarthEarth 1811 gold badge1 silver badge8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 5

Thanks to naththedeveloper from StackOverflow. His answer worked for me.

Well, this was a nightmare to find, but I think I've resolved it after digging through the WordPress code which hooks in through wp_insert_post. Please add this to your functions.php file and check it works:

add_filter('kses_allowed_protocols', function ($protocols) {
    $protocols[] = 'data';

    return $protocols;
});

Essentially internally in WordPress, there's a filter that checks the protocol of any URL's in the content and strips any which it doesn't like. By default, the supported list doesn't support the data protocol. The above function just adds it to the list of supported protocols.

This filter does not run if you're an administrator, which is probably why you're seeing this issue only when logged out.

Thank you for your research.

发布评论

评论列表(0)

  1. 暂无评论