WordPress only allows admin users to save unfiltered HTML in the editor and removes elements for all other user roles that are not specified in a set of allowed elements and attributes. Disallowed elements and attributes, for example, are the svg
element and the sizes
attribute for the img
element. That is a problem when markup generated by a block contains those elements or attributes and leads to interesting results.
For example, if a block generates SVG code depending on user input, let us say a star rating for a review block, we get the following behavior: admin users can add and save the block without problems. Editors can save the block, but get an error when reloading the editor, because the block does not contain the expected markup (because the SVG stars were stripped from the markup).
For me, that happened with a slider block that defines the sizes
attribute for the img
elements. The attribute is not part of the allowed attributes for the img
element, so it is removed for all other roles than admin users.
The problem can be fixed with the wp_kses_allowed_html
filter, that gets an array of allowed tags and attributes, and the context, for example, post
as the context of editing posts and pages. The following code snippet makes the sizes
attribute an allowed attribute for the img
element:
/**
* Allow the img sizes attribute for non-admin backend users in editor.
*/
add_filter( 'wp_kses_allowed_html', function( $allowed_tags, $context ) {
if ( $context !== 'post' ) {
return $allowed_tags;
}
// Add sizes attribute to img.
if ( isset( $allowed_tags['img'] ) ) {
$allowed_tags['img']['sizes'] = true;
}
return $allowed_tags;
}, 10, 2 );
Code language: PHP (php)
Now, also non-admin users can use the block with sizes
attributes without problems.