Why is wp_kses not keeping style attributes as expected?

The question:

I want to keep the style attribute. $str is just an example, here’s my code:

$allowed_html = array(
     'div' => array(
         'title' => array(),
         'class' => array(),
         'style' => array()
    )
);

$str = '<div title='Click to continue' style='display:table'>This is a button</div>';
wp_kses($str, $allowed_html );

$str will actually receive a bunch of html tags and attributes from a post. Then from there i want to strip out all tags and attributes leaving out only divs tags and style and title attributes

Thank you, MMK.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

This is an older question, but here’s the answer for future generations:

WordPress will check the styles against a list of allowed properties and it will still strip the style attribute if none of the styles are safe. The default allow list is:

  • text-align
  • margin
  • color
  • float
  • border
  • background
  • background-color
  • border-bottom
  • border-bottom-color
  • border-bottom-style
  • border-bottom-width
  • border-collapse
  • border-color
  • border-left
  • border-left-color
  • border-left-style
  • border-left-width
  • border-right
  • border-right-color
  • border-right-style
  • border-right-width
  • border-spacing
  • border-style
  • border-top
  • border-top-color
  • border-top-style
  • border-top-width
  • border-width
  • caption-side
  • clear
  • cursor
  • direction
  • font
  • font-family
  • font-size
  • font-style
  • font-variant
  • font-weight
  • height
  • letter-spacing
  • line-height
  • margin-bottom
  • margin-left
  • margin-right
  • margin-top
  • overflow
  • padding
  • padding-bottom
  • padding-left
  • padding-right
  • padding-top
  • text-decoration
  • text-indent
  • vertical-align
  • width

This list is, as with most things in WordPress, filtered! You can add display to it as follows to let your code work as expected:

add_filter( 'safe_style_css', function( $styles ) {
    $styles[] = 'display';
    return $styles;
} );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment