Andrea Gandino

Sanitize CSS in WordPress

Discovering an helper function that sanitizes inline CSS in WordPress.

Published on WordPress

Despite being around since several years, today I've discovered a sanitization helper function within WordPress Core, that performs thorough sanitization of a CSS string.

Originally I believe this function was created to sanitize inline CSS that ended up in elements attributes, but you can clearly apply it even when ensuring that extended inline CSS that ends up in style tags is ok.

The helper function is called safecss_filter_attr, and, apparently, it's been around since version 2.8.1.

The function works pretty much like kses* helpers, in that it dinamically checks the passed string for potentially unsafe/disallowed CSS rules, and strips any of them it should find.

The function also strips the returned string of any potential trailing semicolon.

$css = 'color: red;invalid-property: value';

echo safecss_filter_attr( $css ); // color: red

Just like kses* functions, the logic of the function can be governed via a specific filter, safecss_filter_attr_allow_css, that can be used to determine whether a section of CSS should be allowed or discarded.