How to escape custom css?

I’m creating a WordPress theme in which I’ve allowed users to add some custom css from the Theme Options. This css code then directly gets echoed out in the head section of the page, with the following code:

add_action('wp_head', 'theme_dynamic_css');
function theme_dynamic_css(){
  global $my_theme_options;
  $custom_css="";
  if (isset($my_theme_options['custom-css'])) {
    $custom_css .= $my_theme_options['custom-css']."\r\n";
  }
  echo '<style id="my-theme-custom-css">'.$custom_css.'</style>';
}

Should I be using esc_html(); here? At first I assumed if the code is between the style tags, then it shouldn’t be a problem, but now I’m confused.

Please help.

2 s
2

What you (and probably 99% of the theme authors) are trying to do is just wrong. Users should not be expected to know CSS to customize a theme, and if they do need to go into such a low level, the right thing for them to do is to create a child theme and insert their modifications into its CSS file.

Inputting a CSS in the way you describe is tricky as CSS is not general html and can not be escaped in the same way, but it is also impossible to sanitize and remove potentially insecure code from it. What you end up with is a situation in which you have to output the user’s CSS “as is” in order to be sure you do not break it, but then in the place where such a feature is most useful – multisite, it is too insecure to be used.

Leave a Comment